I want to sum specific elements in an a 2D matrix

1 visualización (últimos 30 días)
N.
N. el 10 de Abr. de 2016
Comentada: sasso samer el 11 de Abr. de 2016
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 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 10 de Abr. de 2016
Editada: Azzi Abdelmalek el 10 de Abr. de 2016
Why the your output is 3x3? And why add the first element to subtract it?
N.
N. el 10 de Abr. de 2016
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

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 10 de Abr. de 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 comentarios
dpb
dpb el 10 de Abr. de 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
sasso samer el 11 de Abr. de 2016
what if i want to do the same thing but on all the numbers not the first 3 numbers only.

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 10 de Abr. de 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);

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by