Question

I have a big 2D matrix of, say, 1000 by 10. I am trying to split that matrix into multiple 2D matrices. They can be 10 by 10, 5 by 10 or 23 by 10. The column size does not change and I am splitting them based on the number in the first column. (In my true case, I do it for the first two columns.) In other words, I'm putting the rows with same id tag, which is the first column value of the vector.

I am trying to achieve this through for loop. And I think it is best to put them into a 'cell array' because cell array allows user to have data in different dimension and different types. So, I want a cell (1-by-varying-N?) where N is the number of matrices split and there are N 2D matrices of varying sizes.

Here my questions are

  1. In this case, should I think the cell as 3-dimension?

  2. How can I initialize a cell with varying dimension?

  3. Given that I have 2D matrix in n-by-m, how can I insert the matrix into a cell?

There are not very many references with varying cell dimension. Any tip / answer would be really appreciated.

Was it helpful?

Solution

Here's a simple example to show you how you can out arrays into cells:

A=cell(2,1); % create a 2x1 cell array
A{1}=ones(3); % put a 3x3 matrix into the first cell
A{2}=rand(5); % put a 5x5 array into the second cell
A{3}=zeros(2); % grow the cell array to 3x1 and put a 2x2 matrix in the third cell
A % see what A looks like

So you can grow cell arrays, for example in a for loop, e.g.:

A=cell(5,1);    
for i=1:5
    A{i}= ...
end

OTHER TIPS

  1. In this case a 3D cell array is not advisable. Just use a 1D cell array and put the 2D arrays inside of it.

  2. You can initialize a cell array using myCell = cell(44,1)

  3. You can populate the cell using myCell{4} = data(1:23, :)

For example, you could write the following bit of code:

% Create some arbitrary data:
data = (1:1000)'*(1:10);
blockSize = 23;

% Create a cell array from scratch:
myCell2 = cell(ceil(1000/blockSize),1);

for ind = 1:ceil(1000/blockSize)
    myCell2{ind} = data((ind-1)*blockSize +1 : min(ind*blockSize, end),:);
end

But I would recommend avoiding the for loop and using the function mat2cell(...) instead like this:

% Create some arbitrary data:
data = (1:1000)'*(1:10);

blockSize = 23;

% Break it up with mat2cell:
myCell = mat2cell(data, [ones(44,1)*23; 11], 10)

% And just for fun, do a calcuation:
cellfun(@norm, myCell)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top