Initialize a field in all elements of a struct array

19 ビュー (過去 30 日間)
shira rez
shira rez 2018 年 8 月 1 日
編集済み: Stephen23 2018 年 8 月 1 日
Hi,
I'm looking for a "one-liner" for initialization of a certain field in an existing struct array. I know that I may achieve this by calling struct(somefiledname,values), or something similar) but I want to initialize all of these additional fields for an existing array of structs, without changing the existing fields.
For example- I have a(1).field1=1; a(2).field1=2; a(3).field1=3;
and I want a one-liner which will add an additional field- "field2" to the "a" struct array (possibly- all ones, all zeros etc.).
Any such shortcut? Or the only way is to iterate through the array?
Thanks!

採用された回答

Stephen23
Stephen23 2018 年 8 月 1 日
編集済み: Stephen23 2018 年 8 月 1 日
Simpler:
[a.field2] = deal(1);
Or if you have multiple items to use:
C = {1,2,3};
[a.field2] = C{:};

その他の回答 (2 件)

Adam Danz
Adam Danz 2018 年 8 月 1 日
編集済み: Adam Danz 2018 年 8 月 1 日
Try this out. It adds a field named 'field2' to each structure and allocates a vector of 4 zeros.
a = arrayfun(@(x) setfield(x, 'field2', zeros(1,4)), a);

James Tursa
James Tursa 2018 年 8 月 1 日
Another way using deal:
[a(1:numel(a)).field2] = deal(4);

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by