How to vectorize assignment of a structure's field value

1 view (last 30 days)
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.

Answers (1)

Jos (10584)
Jos (10584) on 23 Feb 2015
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{:})

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!