Can sections be skipped with something similar to "return" or "continue"?
37 views (last 30 days)
Show older comments
In MatLab live scripts one can split the code into sections. This may be for a visual overview and also allows for running just a specific section at a time instead of the entire code.
I would like to ask if this sectioning is more than visual and practical but also recognizable by the code itself - can the code e.g. treat a section in the same manner as, say, a loop or a function? If so, can a section be skipped by a command similar to what commands such as return or continue do?
So, the question in short is: Is there a way to skip an entire section if a condition is met? Something like:
if ~toggle; _skip this section_; end
Skipping the rest of a function or loop is easy with e.g.:
if ~toggle; return; end
and I am looking for this similar feature for skipping a section. I am asking if this is possible before wrapping an entire section in an if-statement.
0 Comments
Answers (1)
Jared MacDonald
on 4 May 2020
Hi Steeven,
There is currently no way to skip a section other than writing a conditional. This is an intriguing suggestion, though, and we've made a note of it.
Thanks,
Jared
4 Comments
John D'Errico
on 4 May 2020
Edited: John D'Errico
on 4 May 2020
Personally, I think the idea of a branch to skip some section, jumping to a new location down in the code is a bad idea. This just creates a goto. It helps, even encourages the user to write spaghetti code, when a perfectly reasonable solution already exists. (Please don't bring MATLAB back into the bad old days of spaghetti fortran code, when we could jump up, down, back and forth at random.)
So, if they might wish to do something like this:
skip if question is true, to line labeled X
STUFF
X: branch location
then we already have the solution in the form of an if clause:
if question
STUFF
end
There is absolutely no need for a new construct allowing the user to perform a branch to some line label, skipping "stuff".
An even better way to write code like that is to use functions of course. Sean alludes to one way to implement something, by using the editor to hide code. That can also be done using a function to "hide" the offensive code, by putting it all inside a function. Thus we could put stuff into a function. I'll call my function STUFF, whether it be a nested function, a sub-function, an m-file, whatever. Now our code looks much cleaner (though hopefully with a more intelligently chosen name than my uncreative choice of the name STUFF.)
if question, STUFF, end
Sean de Wolski
on 4 May 2020
I agree John. And the refactor capability added a few releases ago to the live editor makes it even easier to convert something to a local or separate file function!
See Also
Categories
Find more on Function Creation 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!