I want to sum specific elements in an a 2D matrix
1 次查看(过去 30 天)
显示 更早的评论
I have a matrix like this
4 3 6 8 1 10 5 2 9
1 10 3 9 4 2 5 7 6
9 5 1 7 8 10 3 4 2
What i want to do is a 3x3 matrix that contains this
For cell (1,1) --- (4 + 8 + 5) - 4 (i.e. 4(the first element in the array) + 8(the fourth element in the array) + 5(the 7th element in the array) - 4(my initial cell))
For cell (1,2) --- (3 + 1 + 2) - 3 (i.e. 3(the second element in the array) + 1(the fifth element in the array) + 2(the 8th element in the array) - 3(my initial cell))
and so on... For cell (2,1) --- (1 + 9 + 5) - 1
It's like calculating the total of all the numbers where the indices are separated by 3
output =
13 3 19
14 11 8
10 12 12
2 个评论
Azzi Abdelmalek
2016-4-10
编辑:Azzi Abdelmalek
2016-4-10
Why the your output is 3x3? And why add the first element to subtract it?
采纳的回答
Star Strider
2016-4-10
A loop is the only way I can see to do this:
M = [4 3 6 8 1 10 5 2 9
1 10 3 9 4 2 5 7 6
9 5 1 7 8 10 3 4 2];
for k1 = 1:3
for k2 = 1:3
S(k1,k2) = sum(M(k1,3+k2:3:end),2);
end
end
S
S =
13 3 19
14 11 8
10 12 12
2 个评论
dpb
2016-4-10
Can do it in only one loop, though...
>> for ic=1:3,S(:,ic)=sum(M(:,ic+3:3:end),2);,end
>> S
S =
13 3 19
14 11 8
10 12 12
>>
accumarray ought to be able to be brought to bear, but it's Sunday afternoon... :)
sasso samer
2016-4-11
what if i want to do the same thing but on all the numbers not the first 3 numbers only.
更多回答(1 个)
Andrei Bobrov
2016-4-10
a =[4 3 6 8 1 10 5 2 9
1 10 3 9 4 2 5 7 6
9 5 1 7 8 10 3 4 2];
n = 3;
out = sum(reshape(a(:,n+1:end),n,n,[]),3);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!