How to vectorize assignment of a structure's field value
1 次查看(过去 30 天)
显示 更早的评论
I have a structure, for example, a 1x5 structure called 'objects' with two fields, and I would like to add a new field, let's call it 'distance', and specify its values, which are stored in a separate array A. I could, of course, use a for loop, e.g.:
for i=1:5
objects(i).distance = A(i);
end
But this doesn't seem very Matlab-y. Is there a vectorized way to do this? I tried objects(:).distance and various other possibilities, but no luck so far.
0 个评论
回答(1 个)
Jos (10584)
2015-2-23
More matlab-y, but completely gibberish for the non-native matlab speaker:
A = 10:10:50
C = num2cell(A)
[objects(1:numel(C)).distance] = deal(C{:})
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!