Combine each row of matrix into a single vector within a cell array

9 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2018-6-17
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

更多回答(1 个)

Sujit Muduli
Sujit Muduli 2018-3-9
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by