How to convert a col array into a struct array field?

I have an struct array with multiplie fields and i want to assign a new field wich values come from a col array of a function.
Example:
Supose that my function returns "a"
a = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
empty_test.a = [];
empty_test.b = [];
test = repmat(empty_test, size(a,1),1);
test.a = a; % Wrong
I want something like this as a result:
test(1).a = 1;
test(2).a = 2;
...
test(10).a = 10;

 採用された回答

Voss
Voss 2022 年 4 月 6 日

0 投票

a = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10];
% 10-by-1 struct array (doesn't need to have a field
% 'a' - doesn't need to have any fields at all in fact):
test = repmat(struct('b',[]),numel(a),1)
test = 10×1 struct array with fields:
b
% assign each element of a to field 'a' of corresponding element of test:
C = num2cell(a);
[test.a] = C{:};
% check the first couple:
test(1)
ans = struct with fields:
b: [] a: 1
test(2)
ans = struct with fields:
b: [] a: 2

1 件のコメント

Vinicius Almeida
Vinicius Almeida 2022 年 4 月 6 日
thanks a lot, num2cell is the answer, because my struct already existed before creating "a"

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by