Filter löschen
Filter löschen

Adding matrices in 4D to 3D

2 Ansichten (letzte 30 Tage)
André Svensson
André Svensson am 7 Sep. 2015
Bearbeitet: Mohammad Abouali am 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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Geoff Hayes
Geoff Hayes am 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.
  1 Kommentar
André Svensson
André Svensson am 7 Sep. 2015
Oh. I've learned so much today, thank you!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by