I want to sum specific elements in an a 2D matrix
1 view (last 30 days)
Show older comments
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 Comments
Azzi Abdelmalek
on 10 Apr 2016
Edited: Azzi Abdelmalek
on 10 Apr 2016
Why the your output is 3x3? And why add the first element to subtract it?
Accepted Answer
Star Strider
on 10 Apr 2016
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 Comments
dpb
on 10 Apr 2016
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
on 11 Apr 2016
what if i want to do the same thing but on all the numbers not the first 3 numbers only.
More Answers (1)
Andrei Bobrov
on 10 Apr 2016
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);
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!