Adding matrices in 4D to 3D
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
André Svensson
le 7 Sep 2015
Modifié(e) : Mohammad Abouali
le 8 Sep 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
0 commentaires
Réponse acceptée
Mohammad Abouali
le 7 Sep 2015
Modifié(e) : Mohammad Abouali
le 7 Sep 2015
total_hitrate_matrix = sum(hitrate_matrix,4)
This adds up the 4th dimension and the resulting matrix would be 7x7x7.
2 commentaires
Mohammad Abouali
le 8 Sep 2015
Modifié(e) : Mohammad Abouali
le 8 Sep 2015
You are welcome. If this concludes your question, would you please accept the answer?
Plus de réponses (1)
Geoff Hayes
le 7 Sep 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.
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!