user1068636
user1068636

Reputation: 1939

How do you split an array in matlab into bins of different sizes within the same data structure?

Suppose I have the following array defined in MATLAB:

x = 1:100;

I would like to form a single data structure "bin" as shown below:

bin(:,1) = x(1:33);  % copy 33 elements into 1st bin
bin(:,2) = x(34:66); % copy another 33 elements into 2nd bin
bin(:,3) = x(67:100);% copy remaining 34 elements into 3rd bin

However, matlab will not allow for the last 34 elements to be added to bin(:,3) since the previous two are of size 33. I would prefer not to use a different variable just to store the last 34 elements. Is there a way in MATLAB to get around this (i.e. how do I use the same data structure "bin" to store all 100 elements in 3 columns of different sizes?)

Upvotes: 1

Views: 248

Answers (2)

Daniel
Daniel

Reputation: 36710

A cell array is a structure which can hold any object, for example arrays of different length. mat2cell allows you to split your array into a cell of several arrays.

bin=mat2cell(x,[33,33,34])

Upvotes: 0

Max
Max

Reputation: 4045

For problems like this, there exist cells. They work like pointers in other languages: one distinguishes between its address and its content. So you can look over the address (which is next to each other) while accessing its content (which may be of different size or type)

bin = cell(1,3); % allocating the cell. not necessary but good practice
bin{1} = x(1:33);  % copy 33 elements into 1st bin
bin{2} = x(34:66); % copy another 33 elements into 2nd bin
bin{3} = x(67:100);% copy remaining 34 elements into 3rd bin

indexing with curly brackets { } will give you the content of the cell, while ( ) gives you the element of the cell (which is obviously a cell). It works like slicing of other variable types. Note that you fit complete arrays into a single element of a cell bin{1} or bin{1,1} returns a 1x33 numeric array.

Upvotes: 2

Related Questions