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!