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

조회 수: 19 (최근 30일)
Tillmann
Tillmann 2018년 3월 6일
답변: Jan 2018년 6월 17일
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에서 Audio and Video Data에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by