How to access elements with same field names in an array of structures without using a loop?
Mostrar comentarios más antiguos
Hello,
Assume we have a cell array of structures:
a.name = 'first';
b.name = 'second';
c.name = 'third';
s = {a; b; c};
Now I want to change the values of fields "name" in some specific structures, for example, in 1 and 3. I know how to do it using a "for"-loop:
ind = [1,3];
replacement = {'whatever', 'word'};
for i = 1:length(ind)
s{ind(i)}.name = replacement{i};
end
Is there a way to do it without a loop? I have found a similar question, but there the author was interested in extracting the data, not in replacing them. Frankly, I am bad in both writing and reading handles' syntaxis, so maybe this answer can be applied to my problem as well, and I just do not see how. Plus, as was mentioned in the comments, cellfun is not faster than a loop - and, at least for me, not easier to read either.
3 comentarios
Stephen23
el 17 de Sept. de 2026 a las 16:41
What are "handles" ?
Paul
el 17 de Sept. de 2026 a las 23:21
Is there an objection to using a for loop?
Wassili Dimitriew
el 18 de Sept. de 2026 a las 7:36
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 17 de Sept. de 2026 a las 17:20
0 votos
1 comentario
Rik
el 18 de Sept. de 2026 a las 19:39
And also this suggestion comes with the caveat that it will be slower than a loop, have more overhead, and will be harder to maintain/update or debug.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!