Avoiding for-loops with subsequent elements in arrays

조회 수: 1 (최근 30일)
Sim
Sim 2020년 6월 9일
댓글: Sim 2020년 6월 9일
Hi, given this
x = [0 10 20 30];
y = [20 10 10 15];
could you suggest a more compact (and faster) way to perform this operation?
A(1) = (y(1) - y(2)) / (x(2) - x(1));
for i = 2 : 4
A(i) = (y(i-1) - y(i)) / (x(i) - x(i-1));
end
Thanks to everyone!

채택된 답변

madhan ravi
madhan ravi 2020년 6월 9일
편집: madhan ravi 2020년 6월 9일
-[0, diff(y) ./ diff(x)]
  댓글 수: 4
madhan ravi
madhan ravi 2020년 6월 9일
eh... well looks like you edited your question after I answered. Before since you didn’t preallocate A MATLAB fills the “first” element with “zero” so...
Sim
Sim 2020년 6월 9일
Yes, sorry, I forgot one line....

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by