Update multiple values in a struct array
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Daniel Dickinson
am 24 Mai 2022
Bearbeitet: Voss
am 24 Mai 2022
I have a struct array S with multiple fields. One of the fields contains numeric values. I want to add a scalar quantity to every entry in this field and overwrite the existing value. I can do this with a loop as follows:
for a = 1:length(S)
S(a).value = S(a).value + 5;
end
Is there a one-line function that does the equivalent?
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (2)
Voss
am 24 Mai 2022
Bearbeitet: Voss
am 24 Mai 2022
This works whether the field is a scalar in each element of S or not:
S = struct('value',{[1 2 3] [2 3; 4 5] [] 6}); % initial struct array
celldisp({S.value});
C = cellfun(@(x)x+5,{S.value},'UniformOutput',false); % perform the additions
[S.value] = C{:}; % assign the result back to the struct array
celldisp({S.value});
0 Kommentare
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!