How to sum n lines of a matrix to another matrix?

조회 수: 4 (최근 30일)
Pedro Vicente
Pedro Vicente 2018년 9월 23일
답변: Kaushik Lakshminarasimhan 2018년 9월 23일
So basically, i have a matrix Apit with the index of (51*n,5,1000) and what i wanted is another matrix TotalApit, with the index (51,5,1000), that sums up 'n' lines by 'n' lines.
like:
if n = 2, Apit(102,5,1000) and TotalApit(51,5,1000)
TotalApit(1,1,1) = Apit(1,1,1)+Apit(2,1,1)
TotalApit(2,1,1) = Apit(3,1,1)+Apit(4,1,1)
So i want that 1 line of TotalApit correspond the sum of n lines of Apit
Can someone help me?
  댓글 수: 2
Image Analyst
Image Analyst 2018년 9월 23일
Explain how the first indexes (row number) are determined on the right hand side. Like why row is 1 and 2 in the first equation, and 3 and 3 (the same) in the second equation. What rule are you using to determine which rows to sum?
And, this is not a big array, just a simple for loop would work, though there are more efficient ways.
Pedro Vicente
Pedro Vicente 2018년 9월 23일
Oh, damn, that was my bad. Should be Apit(3,1,1)+Apit(4,1,1)
I want each line of TotalApit to sum n lines of Apit.

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

채택된 답변

Image Analyst
Image Analyst 2018년 9월 23일
You could do this:
Apit = rand(102,5,1000);
TotalApit = zeros(51,5,1000);
% Now do the sum
[rows, columns, slices] = size(Apit)
n = 2;
tic
k = 1;
for row = 1 : n : rows-n
thisVolume = squeeze(Apit(row:(row+n-1), :, :));
thisSum = sum(thisVolume, 1);
TotalApit(k, :, :) = thisSum;
k = k + 1;
end
toc
Takes a hundreth of a second on my computer. You might be able to do it even faster with convn(). And it would be only 1 or 2 lines of code.

추가 답변 (1개)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2018년 9월 23일
n=2;
TotalApit = reshape(sum(reshape(Apit,[n 102/n 5 1000])),[102/n 5 1000]);

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by