Combine each row of matrix into a single vector within a cell array
9 views (last 30 days)
Show older comments
Hello,
I have a big mxn matrix with m>100,000 and n=1800. Each row of this matrix contains measurement values for a specific point in time. For further processing of the data, I would like to create a mx1 cell array containing the rows of the matrix. Is there a possibility achieving this without a loop?
Here is my code, using a for loop:
A = rand(100000,1800);
b = cell(size(A,1), 1);
for ii = 1:size(b,1)
b{ii,1} = A(ii,1:end);
end
0 Comments
Accepted Answer
Jan
on 17 Jun 2018
This sounds like a job for num2cell.
A = rand(100000,1800);
tic
b = cell(size(A,1), 1);
for ii = 1:size(b,1)
b{ii,1} = A(ii,1:end);
end
toc
Replace "1:end" by the faster ":" :
clear b
tic
b = cell(size(A,1), 1);
for ii = 1:size(b,1)
b{ii,1} = A(ii, :);
end
toc
Compare with num2cell:
clear b
tic
b = num2cell(A, 2);
toc
Even faster without the overhead of num2cell, but operating in columnwise order:
tic
A = A.';
b = cell(size(A,2), 1);
for ii = 1:size(b,1)
b{ii,1} = A(:, ii).';
end
toc
Timings under R2016b, i7, 8GB RAM:
Elapsed time is 3.165280 seconds. Original
Elapsed time is 2.672808 seconds. 1:end -> :
Elapsed time is 2.386299 seconds. num2cell
Elapsed time is 1.717735 seconds. columnwise processing
0 Comments
More Answers (1)
Sujit Muduli
on 9 Mar 2018
Hello Tillmann,
I didn't find any such operation to fill the cell array in one shot without a for loop. I also don't know your exact use case but what I could suggest here is that you don't need to convert it into a cell array. But you can always get a row element of the matrix on demand, by this you may avoid a redundant for loop operation.
But if you could explain your use case and workflow briefly I may suggest you something else.
Thanks
Sujit
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!