Vectorization in an array of structures?

조회 수: 11 (최근 30일)
Francisco de Castro
Francisco de Castro 2012년 7월 11일
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

답변 (2개)

Jan
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.
  댓글 수: 1
Francisco de Castro
Francisco de Castro 2012년 7월 11일
Right... of course, appropriate data types are a must. In my case an array of structures would be the natural choice because I'm building an individual-based ecological model. Each element of the array is an individual, while each field is a trait. Some traits (i.e. prey) are vectors that can be of different lengths for different individuals, making a structure of arrays more difficult to manage than an array of structures. However, given the problems with vectorization I think I'll go with the former and solve the other problems that arise.
Thanks anyway for your advice.

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


Teja Muppirala
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{:});
  댓글 수: 1
Francisco de Castro
Francisco de Castro 2012년 7월 11일
Thanks Teja, but there is not much difference. The time is almost identical than using a loop: 0.002146 sec. vs. 0.002153 sec. for the loop (for a 100-element array).

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by