Add values to a struct element inside a loop

1 回表示 (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by