필터 지우기
필터 지우기

How to access the nested structure inside a nested for loop?

조회 수: 6 (최근 30일)
SK
SK 2018년 8월 5일
답변: Roy Kadesh 2018년 8월 5일
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