Vectorization in an array of structures?

8 次查看(过去 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

回答(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
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
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 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by