how to append inside cells in a cell array without looping?

74 Views Asked by At

I have an array

A={1 6 31 65; 1 38 53 4};

I want a cell array in the form

C={[1 1] [6 6] [31 31] [65 65];[1 1] [38 38] [53 53] [4 4]}; 

One way of doing this is by looping:

for count=1:2
    for i=1:4
        for j=1:2
            C{i,j}(count)=A(i,j);
        end
    end
end

How can I do this without looping and improve time complexity?

Edit: It is not the case for just count=2, I've application where count goes as high as 85. Looping greatly reduces efficiency. And going for higher dimension matrices is also inefficient.

1

There are 1 best solutions below

2
On

One way to do this would be to use cellfun to create each new element

C = cellfun(@(x)ones(1,2) * x, A, 'UniformOutput', false);

As @excaza has pointed out though, you have data of equal sizes so it is recommended that you use a multi-dimensional array instead. You could (for example), just replicate the data along the third dimension instead

C = repmat(A, [1 1 2]);