Assign Field to Structure Array without a Loop

In my routine I create a structure array within a loop like this:
Field1 = [1 2 3];
Field2 = [6 3 1];
for Runner = 1:3
StuctArray(Runner).Field1 = Field1(Runner);
StuctArray(Runner).Field2 = Field2(Runner);
end
As results, in the Variables Window the Structure Array columns are labelled with the field names, which is very convenient to me. However I try in different ways to do it without the loop, but did not succeed. E.g. I tried the following:
StructArray(1:3).Field1 = Field1
I would appreciate any hint how this can be solved without using a loop.

 採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 26 日
編集済み: Bruno Luong 2018 年 10 月 26 日

1 投票

For-loop is alright, but if you insist
Field1 = [1 2 3];
Field2 = [6 3 1];
% Create struct
StructArray = struct('Field1',num2cell(Field1),'Field2',num2cell(Field2))
% Assign to existing struct
Field3 = [4 5 6]
c3 = num2cell(Field3)
[StructArray.Field3] = deal(c3{:});

2 件のコメント

Marius2904
Marius2904 2018 年 10 月 26 日
Thanks a lot! Exactly what I was searching for. Obviously the conversion to a cell array ("num2cell") does the trick.

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2018 年 10 月 26 日
編集済み: Andrei Bobrov 2018 年 10 月 26 日

1 投票

cellarray = num2cell([Field1(:),Field2(:)]);
namefields = {'Field1','Field2'};
StructArray = cell2struct(cellarray,namefields,2);

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2016b

質問済み:

2018 年 10 月 26 日

コメント済み:

2018 年 10 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by