How to address multiple subfields of a structure at once?

2 ビュー (過去 30 日間)
Matthias Stangl
Matthias Stangl 2016 年 10 月 13 日
回答済み: Matthias Stangl 2016 年 10 月 13 日
Hi all,
I have a simple programming question, which might be easy for some of you, but I just can’t find the answer: If I have multiple fields of a structure, how can I address the same variable of multiple subfields at once?
Here is an example:
x(1).a = 10;
x(2).a = 20;
x(3).a = 30;
Now I want a vector of all the a-subfields, like:
result = [10, 20, 30]
I was trying this, but it doesn’t work:
result = x(1:3).a;
Or I want to assign a different value to multiple a-subfields at once. I was trying this, but it doesn’t work:
x(1:3).a = 10;
I know that I can solve this in a for-loop, like:
for i = 1:length(x)
x(i).a = 10;
end
But is there a simpler solution without a loop for this problem?
Thanks!

採用された回答

KSSV
KSSV 2016 年 10 月 13 日
編集済み: KSSV 2016 年 10 月 13 日
You can access the result like:
result = [x(1:3).a]
or
result = [x(:).a]
Replacing the fields I think loop is one option and other way is to use structfun. I tried to implement this but could not get it. Hope some one will answer it.
  1 件のコメント
Stephen23
Stephen23 2016 年 10 月 13 日
Matthias Stangl's "Answer" moved here:
Thats very good and super easy, thanks a lot! However, this only solved the question about "reading" of values. Is there also a similar solution to "write" values, as described in the second part of my question. Or do I actually need to solve this in a loop:
I want to assign a different value to multiple a-subfields at once. I was trying this, but it doesn’t work:
x(1:3).a = 10;
Thanks!

サインインしてコメントする。

その他の回答 (2 件)

Jan
Jan 2016 年 10 月 13 日
[x(1:3).a] = deal(10);

Matthias Stangl
Matthias Stangl 2016 年 10 月 13 日
Perfect, that's exactly what I needed! Many thanks to both of you!

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by