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일
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에 대해 자세히 알아보기

질문:

2022년 4월 6일

댓글:

2022년 4월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by