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;

 采纳的回答

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 个评论

thanks a lot, num2cell is the answer, because my struct already existed before creating "a"

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by