Vectorized way to assign columns/rows of matrix to struct array's field

조회 수: 7 (최근 30일)
Jonas Schütz
Jonas Schütz 2022년 8월 6일
댓글: Jonas Schütz 2022년 8월 6일
Currently I'm using a for loop to assign parts of a matrix to struct's field, like this:
clear
len = 90000;
width = 51;
structArray(1:len) = struct("field",zeros(width,1));
matrixToAssign = rand(width,len);
for i=1:len
structArray(i).field = matrixToAssign(:,i);
end
Because I could vectorize the calculations(not seen here), the assignment of the solutions in the for loop takes an equal amount of time relative to the calculation itself. Is there a way to do the assignment also in a fast vectorized way ?
The calculations I'm doing in this part of the script are depending on len. Typically for examples len>>90000 the accumulated calculations need around 3s and the accumulated assignments need around 2s (calculation and assignment are done multiple times). I have seen something like below, which tends in the right direction but isn't quite what I want to do. I have also seen transformations into cell arrays but I believe those are not faster than the loop method, but maybe I'm wrong.
[structArray.field] = deal(matrixToAssign);

답변 (1개)

Bruno Luong
Bruno Luong 2022년 8월 6일
split = num2cell(matrixToAssign,1);
[structArray.field] = deal(split{;});
  댓글 수: 3
Bruno Luong
Bruno Luong 2022년 8월 6일
편집: Bruno Luong 2022년 8월 6일
IMO If you care about speed, you shouldn't split your array into struct at the first place. It cost you 0 second.
Jonas Schütz
Jonas Schütz 2022년 8월 6일
I guess you are right. I thought there is a faster way to do it. Perhaps I have to take that into consideration.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by