Avoiding for-loops with subsequent elements in arrays

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 投票

-[0, diff(y) ./ diff(x)]

4 件のコメント

James Tursa
James Tursa 2020 年 6 月 9 日
You forgot to fill the (1) spot.
Sim
Sim 2020 年 6 月 9 日
編集済み: Sim 2020 年 6 月 9 日
Thanks Madhan, it is a nice solution :) but it looks like the first term should not be zero...?! ....maybe in this was we get the entire array:
[A(1) -diff(y) ./ diff(x)]
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 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

Sim
2020 年 6 月 9 日

コメント済み:

Sim
2020 年 6 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by