Vectorization in an array of structures?
조회 수: 11 (최근 30일)
이전 댓글 표시
I seem to be unable of vectorize a simple calculation with the contents of an array of structures. Is this possible at all? Example:
S(1).x= 1;
S(2).x= 2;
S(1).y= 0.5;
S(2).y= 0.8;
If i try to do something like this:
S.x= S.x- S.y
I get the error: Too many input arguments.
Also, although [S.x]-[S.y] produces a two-element vector, if I try to assign it to S.x, like this:
S.x= [S.x]-[S.y]
I got the error:
??? Incorrect number of right hand side elements in dot name assignment. Missing [ ] around left hand side is a likely cause.
Things like:
S(:).x= [S.x]-[S.y]
S(1:2).x= [S.x]-[S.y]
Don't work either. Using cell2mat in the result doesn't work.
Is it possible to do something like this without having to do it in a loop? (in a loop, element by element, it DOES work). Do I have to change to a structure of arrays?
Thanks
댓글 수: 0
답변 (2개)
Jan
2012년 7월 11일
편집: Jan
2012년 7월 11일
Vectorization is useful, if the data are represented as vectors (or equivalent arrays). E.g. sin(x) is more efficient than [sin(x(1), sin(x(2)), ..., sin(x(end)). But to process a bunch of fields of a struct and store the results in structs again, I expect a loop to be the fastest method. The creation of the intermediate arrays or cells consumes more time than vectorized calculations can save.
For calculation it is much more efficient to create a scalar struct, which contains arrays as fields, that a struct array, which contains scalar fields. Efficient code is based on a proper choice of the data representation.
Teja Muppirala
2012년 7월 11일
Not sure there's an easy way to do that.
There is this, but I don't see much benefit over using a loop.
N = num2cell([S.x] + [S.y]);
[S.x] = deal(N{:});
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!