Effacer les filtres
Effacer les filtres

Hello, I did a for loop but my friend told me it is not the correct matlab syntax. Can anyone help me the for loop is in the description below:

2 vues (au cours des 30 derniers jours)
for xa=1;
if xa-1>xa & xa+1>xa;
Lm=xa;
else xa=xa+1;
end
end
  2 commentaires
Andy
Andy le 17 Juin 2022
What is it that you are trying to do?
What value of xa can make the if statement True for both conditions (xa-1>xa) and (xa+1>xa)
AbdelRahman Mostafa
AbdelRahman Mostafa le 17 Juin 2022
xa the x axis from 1 to 100 and the y axis is from 1 to 100.

Connectez-vous pour commenter.

Réponses (2)

Chunru
Chunru le 17 Juin 2022
It looks like you want to find the local minima
xa = randn(30, 1);
Lm = nan(size(xa));
for i=2:length(xa)-1
if xa(i-1)>xa(i) && xa(i+1)>xa(i)
Lm(i) = xa(i);
end
end
plot(xa, 'r-');
hold on
stem(Lm, 'bo');

John D'Errico
John D'Errico le 23 Juin 2022
Modifié(e) : John D'Errico le 23 Juin 2022
for xa=1;
This is not a loop. It does nothing but assign the value 1 to the variable xa. NOTHING. No loop.
Instead, it looks like you need to learn about while loops. The loop you TRIED to write wants to continue until you see some event happen. And that is when you use a while loop.
But next, inside the attempted loop you did this:
if xa-1>xa & xa+1>xa;
Look at the first clause in that test. Will it EVER be true that xa-1 > xa? Do you agree that xa-1 must be less than xa? After all, subtracting the number 1 must decrease that number.
Similarly, look at the second clause. Must xa+1 ALWAYS be greater than xa? After all, adding the number 1 increases the value of whatever you add it to.
So what you wrote still makes no sense at all. And that means you need to think about what you wanted to do here, while at the same time learning what a while loop does.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by