For loop difference between two point in a vector

조회 수: 7 (최근 30일)
Ornella Fanais
Ornella Fanais 2018년 5월 21일
댓글: Ornella Fanais 2018년 5월 21일
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!!!! :)

채택된 답변

KSSV
KSSV 2018년 5월 21일
편집: KSSV 2018년 5월 21일
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
Jan
Jan 2018년 5월 21일
편집: Jan 2018년 5월 21일
+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)
Ornella Fanais
Ornella Fanais 2018년 5월 21일
Thank you guys!!!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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