Returning to a particular line in my script

11 views (last 30 days)
hana
hana on 24 Jun 2012
I have an if condition(#3) inside a while loop(#4) that is all together inside another if condition(#1 & 2). if condition 3 is not satisfied, I'd like to divert my code to the second condition of my big if (*) How can I do this?
if condition1
while
...
if condition3
...[go to elseif ~condition1]
end
...
end
elseif ~condition2 *
...
end

Answers (3)

Image Analyst
Image Analyst on 24 Jun 2012
Here's one way. Break the else into it's own separate if, and set a flag for whether or not you need to go inside that if.
testForCondition2 = false;
if condition1
while
...
if condition3
...[go to if ~condition2]
testForCondition2 = true;
end
...
end
end
if testForCondition2 && ~condition2 *
...
end

hana
hana on 24 Jun 2012
the problem is that as soon as condition 3 is satisfied, I have to stop executing and leave " if condition3" as well as the rest of while loop and enter the " if ~condition2 *" I can repeat the entire if ~condition 2 inside the "if condition3" but this is an iterative process and it keeps switching btw. condition1 and ~condition1.
P.S. I found a small typo in my original code! the right code is:
if condition1
while
...
if condition3 % if this is the case, I want to leave and go % right to the * and continue from there
...[go to elseif ~condition1]
end
...
...
end
elseif ~condition1 *
while
....
if condition 4
...[leave and go to if condition1]
end
end
...
end

Image Analyst
Image Analyst on 24 Jun 2012
if condition1
elseif ~condition1
end
is the same as
if condition1
else
end
The code I gave you will let you go into the else block only when you've checked the condition 3. It works because the else is further down the code. But to go from inside the else block back up to the original if line - well that seems weird to me with this type of construct. There is no "goto" in MATLAB so you can't do that. I suggest you rethink this and try to recode this in a different way, like say maybe using functions.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!