Avoiding for-loops with subsequent elements in arrays

1 Ansicht (letzte 30 Tage)
Sim
Sim am 9 Jun. 2020
Kommentiert: Sim am 9 Jun. 2020
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!

Akzeptierte Antwort

madhan ravi
madhan ravi am 9 Jun. 2020
Bearbeitet: madhan ravi am 9 Jun. 2020
-[0, diff(y) ./ diff(x)]
  4 Kommentare
madhan ravi
madhan ravi am 9 Jun. 2020
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 am 9 Jun. 2020
Yes, sorry, I forgot one line....

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by