Reputation: 660
In Matlab I got three matrices (consisting of vectors) x, y, z
of size 3xn
each.
I want to merge them to a cell with n
entries, each a 3x3
matrix:
for i=1:n
C{i} = [x(:,i), y(:,i), z(:,i)];
end
Is there a faster way than using this for loop, because that takes ages?
I already found functions like mat2cell
and cellfun
, but they all don't really do what I need, do they?
Upvotes: 0
Views: 104
Reputation: 2303
Try this:
t = reshape([x; y; z], [3 3*n]); %//reshape your vectors into a matrix that could be use nicely with mat2cell
C = mat2cell(t, 3, 3*ones(1,n));
Upvotes: 2
Reputation: 14927
Unless the code you are calling demands it, use a 3D array instead. It comes with much less overhead.
C = zeros(3, 3, n);
for ii = 1:n
C(:, :, ii) = [x(:,ii) y(:,ii) z(:,ii)];
end
In this form, you can vectorize it instead, using reshape
:
C = reshape([x; y; z], [3 3 n]);
Upvotes: 4
Reputation: 2114
You can pre-allocate the memory the improve performance:
C = cell(n, 1);
Upvotes: 0