Add values to a struct element inside a loop
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi everyone, I have a vector (B) that contains some values that are repeated and to each value of B corresponds a value of the vector C. For each values of A (from 1 to 5) i want to create a structure element (and store them into a 5x1 cell element) that contains one field (fieldname) with the values of C.
A=[1:5];
B=[1 2 3 4 4 5 4];
C=[10 10 10 10 20 10 30];
for example for the value 1 of A i want a structure 1x1 with field 'fieldname' and value 10 while for the value 4 of A i whant a structure 1x3 with value 10, 20, 30 assigned to the field.
I have tryed this scrip
A=[1:5];
B=[1 2 3 4 4 5 4];
C=[10 10 10 10 20 10 30];
E=cell(length(A),1);
a='fieldname';
for i=1:length(A)
for r=1:length(B)
if A(1,i)==B(1,r)
E{i,1}=struct(a,C(1,r));
end
end
end
The problem is that i only obtain 1x1 structure element because the loop overwrites the element in E{i,1} position instead of adding another value to the field. So in position E{4,1} i have a 1x1 struct element with value 30 assigned to the field instead of 1x3 struct with values 10, 20, 30. Someone can help me??
댓글 수: 2
Jan
2018년 8월 4일
Do you really want a cell array of structs? If all structs have the same field, a struct array would be smarter.
답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!