How to access elements with same field names in an array of structures without using a loop?
显示 更早的评论
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 个评论
Stephen23
2026-9-17,16:41
What are "handles" ?
Paul
2026-9-17,23:21
Is there an objection to using a for loop?
Wassili Dimitriew
2026-9-18,7:36
采纳的回答
更多回答(1 个)
Walter Roberson
2026-9-17,17:20
0 个投票
1 个评论
Rik
2026-9-18,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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!