Effacer les filtres
Effacer les filtres

subtract each element from the one before in a row matrix

7 vues (au cours des 30 derniers jours)
Lama Hamadeh
Lama Hamadeh le 31 Juil 2021
Modifié(e) : Cris LaPierre le 31 Juil 2021
Hi all,
I have a row matrix defined as:
s = linspace(0,4,17);
I want to create a vector that its elements are the half subtraction of two subsequent elements of vector s. My attempt to do that is the follwoing:
for i = 1:length(s)-1
for j = 2:length(s)
Mid_s = (s(j)-s(i))/2;
end
end
However, the result I'm having is just one number. How can I have all numbers resulted from the "for" loop as an array/vector?
Thanks.

Réponses (1)

Cris LaPierre
Cris LaPierre le 31 Juil 2021
Modifié(e) : Cris LaPierre le 31 Juil 2021
You are overwritting your variable Mid_s everytime, so you just end up with the very last number. Ch 13 of MATLAB Onramp will introduce you to writing for loops.
As a suggestion for improvement, you can accomplish this with a single for loop. Even better, you should look into the diff command.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by