Set multiple fields of a struct to a certain value?

33 ビュー (過去 30 日間)
Thomas Fab
Thomas Fab 2022 年 2 月 15 日
コメント済み: Image Analyst 2022 年 2 月 15 日
Hi Guys,
I need to set multiple fields of a struct to a certain value.
For example:
pressdata(1).refF1 = 1000
pressdata(2).refF1 = 1000
pressdata(3).refF1 = 1000
pressdata(4).refF1 = 1000
Is there any way to make this more elegant within 1 line?
pressdata(1:4).refF1 = 1000
...does not work :(
A loop seems kind of overkill:
for x=1:4
pressdata(x).refF1 = 1000
end
Thanks,
Thomas

採用された回答

Stephen23
Stephen23 2022 年 2 月 15 日
編集済み: Stephen23 2022 年 2 月 15 日
"Set multiple fields of a struct to a certain value?"
What your example shows is how to set one field of multiple elements of a structure array. Lets try it.
pressdata(1).refF1 = 1;
pressdata(2).refF1 = 2;
pressdata(3).refF1 = 3;
pressdata(4).refF1 = 4;
You can set one field of zero, one, or more elements of the structure array like this:
[pressdata.refF1] = deal(1000)
pressdata = 1×4 struct array with fields:
refF1
For more information on how this works:

その他の回答 (1 件)

Daniel Catton
Daniel Catton 2022 年 2 月 15 日
You could do a loop but on just the one line?
for x=1:4; pressdata(x).refF1 = 1000; end
  1 件のコメント
Image Analyst
Image Analyst 2022 年 2 月 15 日
Perhaps this is more intuitive, and maintainable should you need to give the code to other people. Most people would have to look up what the deal() function does, while this is obvious.

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

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by