How to create for and if loops instead of while

Hi all,
I am quit new to matlab and wondering if possible to write for with if loop instead of while: (as It is required to link that file to another programme that does not read while.
So here is the matlab code example:
x = 1;
st = 0;
y = 1;
z = 1;
while y <= 20
switch (st)
case 1
display('CASE ONE')
st = 2;
case 2
while display('CASE TWO')
end
st = 3;
otherwise
display('OTHERS')
end
end
Hope anyone can help and guide me how to write the same example but without while loop

2 Kommentare

Image Analyst
Image Analyst am 21 Okt. 2022
Bearbeitet: Image Analyst am 21 Okt. 2022
That's an infinite loop because you never change y within the loop. You need to change y or else the loop will never exit. What is your equation for how y changes?
Invest 2 hours here:
Jan
Jan am 21 Okt. 2022
Note, that "if loop" is not a meaningful expression.
The current code displays 'OTHERS' in an infinite loop. What is the intention to modify the code?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Jan
Jan am 21 Okt. 2022
WHILE and FOR loops are equivalent:
k = 1;
while k <= 100
...
k = k + 1;
end
and
for k = 1:100
...
end

4 Kommentare

Mark Sc
Mark Sc am 21 Okt. 2022
Thank you for your prompt reply.
May I ask what is the meaing of switch (st) in the code ??
What is the meaning of cases ?? if it something like if ??
how can I terminate the loop ?
The intent os modifying the code with for and if is as I had mentioned earlier, that code should work in other program which does not suppport while statement
So I wish you could help me.. if possible and tell me more what is the meaning of both switch and case
Thanks,
switch, case, otherwise is basically like a bunch of if/elseif blocks.
Mark Sc
Mark Sc am 21 Okt. 2022
Thanks! got it...
but just a question how can I exit without the need to repeat 100 iteration..
I mean I understand I have to add if
but what if I found what I am looking how can I stop and go out from the loop
@Mark Sc in a for loop or while loop you test some condition and then call break to immediately leave the loop.
for k = 1 : 10000
if iWantToExitLoop
break; % Bail out of for loop completely. Also works with while loops.
end
end
Not sure what condition you want to check to bail out, but that's basically it.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 21 Okt. 2022

Kommentiert:

am 21 Okt. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by