Add values to a struct element inside a loop

조회 수: 3 (최근 30일)
Federico Selvi
Federico Selvi 2018년 8월 4일
댓글: Federico Selvi 2018년 8월 4일
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
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.
Federico Selvi
Federico Selvi 2018년 8월 4일
I don't konow if using the cell array it's the best solution but I'have used it to store the different struct element because i need one of them for each value of the vector A even if they have all the same field. So in this way i want to obtain a 1x1 struct for the value 1, a 1x1 for the value 2 and so on and for the value 4 i need a 1x3 struct

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2018년 8월 4일
편집: Jan 2018년 8월 4일
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 k = 1:length(A)
E{k} = struct(a, C(B == A(k)));
end
Maybe this helps:
CellResult = accumarray(B.', C, [5,1], @(x) {x})
StructResult = cell2struct(CellResult, a, 2)
  댓글 수: 2
Federico Selvi
Federico Selvi 2018년 8월 4일
thank you, now it's better but the problem remains that the struct element for the value 4 is still a 1x1 (even if it contanis the 3 values 10 20 30). I need it to be a 1x3
Federico Selvi
Federico Selvi 2018년 8월 4일
I'have found a solution. I need to write C as a cell element instead of a normal vector.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by