How can i vectorize this assignment to a structure array?
조회 수: 5 (최근 30일)
이전 댓글 표시
Hello everyone, I have initialized a structure array like this:
[v(1:5).s] = deal( false(1, 3) );
Now, I would like to modify only certain elements of it. And I can do it with a for loop, like this:
idv = [2 4 5]; % v indexes
ids = [1 1 3]; % corresponding s indexes where to write
for i=1:length(idv)
v( idv(i) ).s( ids(i) ) = true;
end
Is there a way to vectorize this operation?
If not, can I at least vectorize this one?
for i = 1:NoP
vm(i).s = false(size(vm(i).v));
end
Thank you very much!
댓글 수: 0
답변 (2개)
Jan
2013년 9월 12일
편집: Jan
2013년 9월 12일
If idv is large and not unique, finding corresponding elements at first can increase the speed under some conditions. If idv is unique, the only way to improve the speed is to use a smarter structure for your data. The vectors idv and ids are a very compact and efficient way to store the positions of the enabled bits already. Inflating this structure by using a struct array with multiple fields, the performance must degrade and even a hyper-intelligent vectorization cannot lead to really fast code.
[EDITED] The 2nd loop ("for i = 1:NoP") cannot be vectorized also. And even if there would be a method, it could not be remarkably faster than the loop.
A vectorization is efficient, when the same procedure can be applied to an array of data instead of processing each element independently. Example:
a = [sin(1.1), sin(1.2)] % "Slow" elementwise operation
b = sin([1.1, 1.2]) % "Fast" vectorized code
But setting a field of a struct array to different values does not allow to combine any data to a continuous block.
댓글 수: 0
Azzi Abdelmalek
2013년 9월 11일
I think your for loop is the better way to do it. Are you trying to make your code faster?
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!