How to access elements with same field names in an array of structures without using a loop?
Ältere Kommentare anzeigen
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 Kommentare
Stephen23
am 17 Sep. 2026
What are "handles" ?
Paul
am 17 Sep. 2026
Is there an objection to using a for loop?
Wassili Dimitriew
am 18 Sep. 2026
Akzeptierte Antwort
Weitere Antworten (1)
Walter Roberson
am 17 Sep. 2026
0 Stimmen
1 Kommentar
Rik
am 18 Sep. 2026
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.
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!