how can I do this mathmatical operation?

I wish to do sum and subtract in column 2 of 84x7 matrices between different rows of the element on the same column and produce the answers into an array. example @Column 3, a = [ 1 3 3 3 ; 2 2 2 2 ; 3 4 4 4 ; 4 0 1 0 ; 5 5 5 5 ; 1 1 1 1 ; 7 7 7 7 ] desired outcome: => b = [ 3 7 10 ]

5 comentarios

madhan ravi
madhan ravi el 22 de Oct. de 2018
Editada: madhan ravi el 22 de Oct. de 2018
b = [ 3 7 10 ] is not clear
Young Lee
Young Lee el 22 de Oct. de 2018
Editada: Rik el 22 de Oct. de 2018
(a(1,3) - a(2,3)) + (a(3,3) - a(2,3)) = b(1) = 3
(a(3,3) - a(4,3)) + (a(5,3) - a(4,3)) = b(2) = 7
this continues until length(a)
Rik
Rik el 22 de Oct. de 2018
Could you show more of the calculation steps? The calculation is not clear to me. The sum of the columns is [23 22 23 22], so I don't see how any subtraction would result in your output.
Kevin Chng
Kevin Chng el 22 de Oct. de 2018
Editada: Kevin Chng el 22 de Oct. de 2018
I guess what you want is
for i=1:2:(length(a(:,3))-2)
b(i)= a(i,3)-a(i+1,3)+(a(i+2,3)-a(i+1,3))
end
b(2:2:end)=[];
Why length(a(:,3)-2)? It is to avoid exceed the dimension.
Young Lee
Young Lee el 23 de Oct. de 2018
Thanks that worked out perfectly with little change @@

Iniciar sesión para comentar.

 Respuesta aceptada

Kevin Chng
Kevin Chng el 22 de Oct. de 2018
I guess what you want is
for i=1:2:(length(a(:,3))-2)
b(i)= a(i,3)-a(i+1,3)+(a(i+2,3)-a(i+1,3))
end
b(2:2:end)=[];
Why length(a(:,3)-2)? It is to avoid exceed the dimension.

2 comentarios

Jan
Jan el 22 de Oct. de 2018
Use size(a, 1) instead of length(a(:, 3)), because it is more efficient and nicer.
Rik
Rik el 22 de Oct. de 2018
To expand a bit on Jan's comment: using length can get you into trouble, because it is equivalent to max(size(A)). That means that you need to be sure that the dimension that is relevant for you will always be the largest. Using size with a specified dimension will avoid this problem. If you want to iterate through all elements of a vector, it is safest to use numel, which is equivalent to prod(size(A)).

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 22 de Oct. de 2018
Editada: Jan el 22 de Oct. de 2018
This works without a loop:
n = size(a, 1);
b = a(1:2:n-2, 3) - 2 * a(2:2:n-1, 3) + a(3:2:n, 3)

Categorías

Más información sobre Data Preprocessing en Centro de ayuda y File Exchange.

Preguntada:

el 22 de Oct. de 2018

Comentada:

el 23 de Oct. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by