Search code examples
matlabcell-array

How to create doubles from cell arrays?


I would like to ask if there is a more efficient code to do the following task:

a = cell(10,1); 

for i = 1 : 10
a{i,1} = randn(200,5);
end

for j =1:5
b{j} = [a{1,1}(:,j) a{2,1}(:,j) a{3,1}(:,j) a{4,1}(:,j) a{5,1}(:,j)];
end

Thank you!


Solution

  • Your solution works just fine. This is slightly more compact (and easier to generalize). If all cells contain matrices of the same size, you can merge them in one matrix, and pick one column every n:

    for i = 1 : 10
        a{i,1} = randn(200,5);
    end
    
    % Transform first five cells in one big matrix
    c = cat(2,(a{1:5}));
    n = size(a{1} , 2);
    
    b = cell(5,1);
    for j =1:5
        % Take one column every 5 (or every "n" in general)
        b{j} = c(: , 1:n:end );
    end