How to access the nested structure inside a nested for loop?
1 次查看(过去 30 天)
显示 更早的评论
Hi, i am trying to find the mean of the structure. but the error it displays is "Index exceeds array bounds". The size of H is 1x35 struct and the size of G is 1x19.
for i = 1:35
for j= 1:19
A = mean([H(i).G{1,j}]);
end
X(i) = mean(A(j));
i=i+1;
end
2 个评论
Roy Kadesh
2018-8-5
In your loop, you assign the mean of the cell contents to A. This will only be a vector if the cell contents are a matrix. So when you call mean(A(j)), A will generally be a scalar.
Also, you don't need i=i+1; in a for-loop (Matlab does that for you), and the result of A is only used after the last iteration.
Please provide a sample input and the desired output so we can write working code.
回答(1 个)
Roy Kadesh
2018-8-5
See if this works. If the input data is not similar to your data or the output is not as desired, please write some code that generates usable data and explain what the expected output should be.
%create random data to have a valid input
H=struct;
for H_ind=1:35
for G_ind=1:19
H(H_ind).G{1,G_ind}=rand(10,1);
end
end
%calulate mean of means for each struct element
X=zeros(1,35);
for i = 1:35
A=zeros(1,19);
for j= 1:19
A(j) = mean([H(i).G{1,j}]);
end
X(i) = mean(A);
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!