Vectorization in an array of structures?

10 views (last 30 days)
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

Answers (2)

Jan
Jan on 11 Jul 2012
Edited: Jan on 11 Jul 2012
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 Comment
Francisco de Castro
Francisco de Castro on 11 Jul 2012
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.

Sign in to comment.


Teja Muppirala
Teja Muppirala on 11 Jul 2012
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 Comment
Francisco de Castro
Francisco de Castro on 11 Jul 2012
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).

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!