How to access elements with same field names in an array of structures without using a loop?
Show older comments
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 Comments
Stephen23
on 17 Sep 2026 at 16:41
What are "handles" ?
Paul
on 17 Sep 2026 at 23:21
Is there an objection to using a for loop?
Wassili Dimitriew
on 18 Sep 2026 at 7:36
Accepted Answer
More Answers (1)
Walter Roberson
on 17 Sep 2026 at 17:20
0 votes
1 Comment
Rik
9 minutes ago
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.
Categories
Find more on Programming Utilities in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!