Add values to a struct element inside a loop
1 回表示 (過去 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 件)
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)
参考
カテゴリ
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!