MATLAB Answers

Can sections be skipped with something similar to "return" or "continue"?

조회 수: 12(최근 30일)
Steeven 13 Apr 2018
댓글: Sean de Wolski 4 May 2020
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

Sign in to comment.


Jared MacDonald
Jared MacDonald 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.

  댓글 수: 4

표시 이전 댓글 수: 1
John D'Errico
John D'Errico 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
X: branch location
then we already have the solution in the form of an if clause:
if question
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
Sean de Wolski 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!

Sign in to comment.

Translated by