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!