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
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.
SK
SK 2018-8-5
Thank you for pointing out about A(j) however it still shows the same error. The structure was built according to the information: G is a variable representing 1x19. H is a variable that represents a 1x35 structure. this data would be the input. so this structure should run as follows. G should iterate for 19 times and the mean of that A(j) should be stored in X(i) then the H should iterate for 35 times.(for each H the G has to iterate 19 times).

请先登录,再进行评论。

回答(1 个)

Roy Kadesh
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

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by