フィルターのクリア

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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by