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

5 visualizaciones (últimos 30 días)
SK
SK el 5 de Ag. de 2018
Respondida: Roy Kadesh el 5 de Ag. de 2018
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 comentarios
Roy Kadesh
Roy Kadesh el 5 de Ag. de 2018
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 el 5 de Ag. de 2018
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).

Iniciar sesión para comentar.

Respuestas (1)

Roy Kadesh
Roy Kadesh el 5 de Ag. de 2018
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

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by