Update multiple values in a struct array

13 visualizaciones (últimos 30 días)
Daniel Dickinson
Daniel Dickinson el 24 de Mayo de 2022
Editada: Voss el 24 de Mayo de 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?

Respuesta aceptada

Matt J
Matt J el 24 de Mayo de 2022
Editada: Matt J el 24 de Mayo de 2022
No, but easy enough to make one:
[s(1:2).f]=deal(1,2);
s.f
ans = 1
ans = 2
s=incremStruct(s,'f',5);
s.f
ans = 6
ans = 7
function S=incremStruct(S,field,increm)
for i = 1:length(S)
S(i).(field) = S(i).(field) + increm;
end
end

Más respuestas (2)

Matt J
Matt J el 24 de Mayo de 2022
Editada: Matt J el 24 de Mayo de 2022
You can do it in 2 lines,
C=num2cell([S.value]+5);
[S.value]=deal(C{:})

Voss
Voss el 24 de Mayo de 2022
Editada: Voss el 24 de Mayo de 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});
ans{1} = 1 2 3 ans{2} = 2 3 4 5 ans{3} = [] ans{4} = 6
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});
ans{1} = 6 7 8 ans{2} = 7 8 9 10 ans{3} = [] ans{4} = 11

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by