# A simple question on matlab

1. Jan 13, 2012

### matler

I'm not very familiar with matlab, trying to learn it little by little by watching some tutorials. However to be able to figure out how it works I need some samples. So, here what I'm trying to do is create a function which takes a matrix, say B matrix, and then divides it into three range;
[0 10), [10 100), and [100 1000)
Then it puts those arrays into 3 different 1x3 cells

Suppose A = [2,4,100,50,40,800]
cell1 = 2,4
cell2 = 40, 50
cell3 = 100, 800

Like that.
Is it possible anyone to create that function, thus I can inspect it to understand the structure.
Suppose not a big deal for someone who's familiar with matlab.

Thanks in advance for any attempt of help

2. Jan 13, 2012

### mikeph

My answer would depend on the scale and variables of the problem, but a simple answer for this specific problem might be:

Code (Text):
[2,4,100,50,40,800];
c=[];d=[];e=[];

for i = 1:numel(A)
if 0 <= A(i) && A(i) < 10
c(numel(c) + 1) = A(i);
elseif 10 <= A(i) && A(i) < 100
d(numel(d) + 1) = A(i);
elseif 100 <= A(i) && A(i) < 1000
e(numel(e) + 1) = A(i);
end
end
This creates three empty vectors (c,d,e) and then loops through all the elements of A using an index i. If an element of A is found to be in the range [0,10), the first element of c is set equal to it, the same with the ranges [10,100) for d and [100,1000) for e. If a second element is found to be in the range [0,10) then the second element of c is set equal to it, this is done using "numel(c) + 1" which finds the number of current elements in c and creates a new element. For example if there are 7 elements in c, numel(c)+1 = 8 and so c(8) is assigned the next value, increasing its size.

This code is fairly basic and has two major flaws, first, it is not adaptable for varying number of bins (you must manually set c,d,e), and second, if you have a large number of elements in A, the method of binning, which increases the bins as the loop progresses, is very slow, because when you extend a vector MATLAB must create a new vector, copy, then delete the old one. Extending a large vector many times uses huge memory bandwidth. (see: preallocating)

For a larger solution I would try to use the "sort" function, possibly alongside the "histc" function to sort the entire set of elements, then bin them automatically. The MATLAB help should give a good explanation of those two functions.