Search code examples
matlabcellreshape

Reshaping cells: transform a 1xj cell with i observations into a 1xi cell with j observations


I want to know the best practice to reshape cells.

Let's say I have a 1x5 cell that has 2 observations in each cell. In my example, I will this cell VAR. In order to run an example:

cbar=linspace(0,1,2);
for i=1:5
    for j=1:2
VAR{i}(j)=i+cbar(j);
    end
end

Let's say I want to create another cell that will be 1x2 and will have 5 observation in each cell -so I am reshaping the VAR cell above. The way I am approaching this, which is not working, is the following

for i=1:5
    for j=1:2
   VAR_new{j}(i)=VAR{i}(j);
    end
end

It happens that for some reason the VAR_new is empty.

How can I do this properly? Thank you!


Solution

  • You can combine reshape to reshape the matrix to the desired dimensions, and mat2cell to convert the matrix to a cell array:

    VAR_new = mat2cell(reshape([VAR{:}],5,[]),5,repelem(1,2));
    
    >> VAR_new
    
    VAR_new =
    
      1×2 cell array
    
        {5×1 double}    {5×1 double}
    
    >> VAR_new{1}
    
         1
         2
         2
         3
         3
    
    >> VAR_new{2}
    
         4
         4
         5
         5
         6