Borrar filtros
Borrar filtros

Adding matrices in 4D to 3D

2 visualizaciones (últimos 30 días)
André Svensson
André Svensson el 7 de Sept. de 2015
Editada: Mohammad Abouali el 8 de Sept. de 2015
I have a matrix that is 7x7x7x5 at the moment, and now I want to add the last dimension matrices together, making a final matrix 7x7x7 but I'm having trouble making this loop. The matrices I want to add together are A(:,:,k,1:5) for the index k that goes from 1:7.
I can add these in the prompt window like this for example;
A(:,:,1,1)+A(:,:,1,2)+A(:,:,1,3)+A(:,:,1,4)+A(:,:,1,5);
A(:,:,2,1)+A(:,:,2,2)+A(:,:,2,3)+A(:,:,2,4)+A(:,:,2,5);
and so on. But how to I make this in a loop with index k for the 3rd dimension, and another index for the 4th dim?
So far my code looks like this(and I know it exceeds matrix dim, but just to exemplify a bit):
total_hitrate_matris=zeros(7,7,7);
for k = 1:7
for l=1:5
total_hitrate_matris(:,:,k)=total_hitrate_matris(:,:,k,l)+hitrate_matris(:,:,k,l+1);
end
end

Respuesta aceptada

Mohammad Abouali
Mohammad Abouali el 7 de Sept. de 2015
Editada: Mohammad Abouali el 7 de Sept. de 2015
total_hitrate_matrix = sum(hitrate_matrix,4)
This adds up the 4th dimension and the resulting matrix would be 7x7x7.
  2 comentarios
André Svensson
André Svensson el 7 de Sept. de 2015
Thank you, that was exactly what I wanted. And no loop needed! Much better!
Mohammad Abouali
Mohammad Abouali el 8 de Sept. de 2015
Editada: Mohammad Abouali el 8 de Sept. de 2015
You are welcome. If this concludes your question, would you please accept the answer?

Iniciar sesión para comentar.

Más respuestas (1)

Geoff Hayes
Geoff Hayes el 7 de Sept. de 2015
André - I think that you have the right idea, it is just how you go about initializing the total_hitrate_matris(:,:,1) which is causing the problem. Taking your above code, we can try the following
hitrate_matris = randi(255, 7, 7, 7, 5);
total_hitrate_matris = zeros(7,7,7);
for u=1:size(hitrate_matris,3)
% initialize total_hitrate_matris(:,:,u) and then sum the remaining
% dimensions
total_hitrate_matris(:,:,u) = hitrate_matris(:,:,u,1);
for v=2:size(hitrate_matris,4)
total_hitrate_matris(:,:,u) = total_hitrate_matris(:,:,u) + hitrate_matris(:,:,u,v);
end
end
Note how we just add the remaining dimensions (from 2 to 5) to total_hitrate_matris(:,:,u) at each iteration of the inner for loop.
  1 comentario
André Svensson
André Svensson el 7 de Sept. de 2015
Oh. I've learned so much today, thank you!

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by