image thumbnail

MATLAB Goto Statement

version 1.8.0.0 (9.21 KB) by Husam Aldahiyat
The one and only.

6.2K Downloads

Updated 17 Feb 2011

View License

It goes without saying that this code is mainly just for entertainment purposes, since using goto() is considered lazy programming and is a debugging nightmare. With that out of the way, I present to you goto.m, similar to the goto() or jump() commands in other programming disciplines.

Syntax:

goto(pointer,file)
return % All goto() commands need to be followed by a 'return'!

pointer could be an integer representing a line number in the m file, a string addressing a label in the m file, an array consisting of line numbers to consecutively jump to, or a cell array consisting of label strings to jump to. Using inf as an input jumps to the end of the code, while using NaN jumps to a randomly chosen line number (credit to Loren for the not-so-deliberate inspiration).

The second input, file, is optional. It states the code file to which the we want to jump to (default is current m file).

Twenty four example files are accompanied in the zip folder. Check the usage of this function inside them in order to understand how to implement goto() in your own routines. An example is shown below.

Example 23:

labels = {'add';'init1';'add';'add';'show'};

goto(labels)
return

% LABEL init1
a = 0;
goto('End')
return

% LABEL add
a = a + 1;
goto('End')
return

% LABEL init2
a = 0;
goto('End')
return

% LABEL show
msgbox(num2str(a))

% LABEL End

Cite As

Husam Aldahiyat (2021). MATLAB Goto Statement (https://www.mathworks.com/matlabcentral/fileexchange/26949-matlab-goto-statement), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2007b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories

Community Treasure Hunt

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

Start Hunting!