필터 지우기
필터 지우기

Adding matrices in 4D to 3D

조회 수: 2 (최근 30일)
André Svensson
André Svensson 2015년 9월 7일
편집: Mohammad Abouali 2015년 9월 8일
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

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2015년 9월 7일
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
André Svensson
André Svensson 2015년 9월 7일
Oh. I've learned so much today, thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by