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
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?
N.
N. 2016-4-10
I added the first element to subtract it to not lose the sequence. and 3x3 the first 3 is the number of rows, the second 3 depends on the distance between the indices which means that if i want to add the elements every 4 indices on a bigger matrix then i will have a 3x4 matrix

请先登录,再进行评论。

采纳的回答

Star Strider
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
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
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
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 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