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;

 Accepted Answer

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 Comment

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

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!