For loop difference between two point in a vector

Hi everyone! I have a problem, I have to do a difference between two point: I have this vector for example M=[1;2;4;6;7;8] and my for loop should be able to construct this vector [2-1;4-2;6-4;7-6;8-7]. I'm using this script, but It's worng
for i=M(0):length(M)-1
inc=M((i)+1)-M(i);
end
I'm hoping you can help me. Thanks!!!! :)

 Respuesta aceptada

KSSV
KSSV el 21 de Mayo de 2018
Editada: KSSV el 21 de Mayo de 2018
iwant = diff(M)
If you are adamant about loop:
M = [1;2;4;6;7;8] ;
N1 = [2-1;4-2;6-4;7-6;8-7] ;
N = zeros(length(M)-1,1) ;
for i = 1:length(M)-1
N(i) = M(i+1)-M(i) ;
end

2 comentarios

Jan
Jan el 21 de Mayo de 2018
Editada: Jan el 21 de Mayo de 2018
+1. Perfect. The efficient diff is mentioned and the problem of the loop is explained.
Another solution:
N = M(2:end) - M(1:end-1)
Thank you guys!!!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 21 de Mayo de 2018

Comentada:

el 21 de Mayo de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by