File Exchange

image thumbnail

MATLAB Goto Statement

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

26 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

Comments and Ratings (51)

amr mousa

Mahesh Talwar

I get the error Undefined function or variable 'goto' in 2013(b)...whats is the solution ?

Thanks Husam for posting this ! Your examples work well in my computer (2017a and 2013a), but not in the code that I am working on. Originally the code is Fortran 77 with a lot of GoTos, which I have converted to matlab resulting in a multi-nested code, that when I ran your function I get the error:
Error in goto (line 510) if ~(where-var ==length(num_range)....

Any idea on how to solve this problem is greatly appreciated ... thanks !

Kobi Bilou

Thanks, Well worked

Especially Example 1 to go at spécifique line in the script

ANOOP S

while clicking on the run icon, its showing an error message, 'Syntax error : "filename" can't run as it appears. Enter input arguments by typing them now, then press enter to run. the value you enter will be set as the default inputs when you click the run button in the future'. I dont understand what it means. I use the goto(pointer) type command. MATLAB2015a

Min Adhikari

this is awesome

tabw

tabw (view profile)

it won't work in R1010b Matlab.
I don't know why. I tried your example. But matlab crashed when running the goto().

Amit

Amit (view profile)

@Iylia: The full code is too long, the relevant part would be:
% LABEL num
...
...
if condition
goto('num')
return
end
...

lylia

lylia (view profile)

@Amit: what did you write exactly ??

Amit

Amit (view profile)

Getting the following error:
Error using goto (line 637)
Error: At least one END is missing: the statement may begin here.

lylia

lylia (view profile)

Thank you, thank you so much!!! I'm using Matlab R2013b, and the function works perfectly, it does exactly what it is supposed to do. Took me some time to know how to use it properly,but I guess that I was overjoyed when I found this function that I didnt read carefully the description. :p :p I had no other choice but to use a goto function. Thank you again :D

Hi Husam.. The error was that i never was able to run the code within my code. i was however able to run it without issue in many other applications mainly for testing purposes but for this specific application it was not functioning..

Like John said, this function should only be used in very special cases where you'd write your entire code around the goto() function, like in MoDu's thesis, which is a very special code. Either that or if you just want to have some fun and explore alternative far out MATLAB functionality. That said, you didnt' even write the error, what did it say?

Hi John,

Thank you so much! It works!!! I totally agree with your suggestion but i'm just puzzled how i could have missed out such a simple solution and went around everywhere looking for something much more complex!!

Nevertheless.. Thanks again and Cheers!

John D'Errico

Chockalingham - You are misusing what is already a tool that should be avoided. Instead, learn to use while. Your code will improve. It will speed up. It will become more readable and more bug free.

Hi,

Could you kindly clarify the following application of the 'goto' statement please.

I would like to compare random values to an array and generate a new array and am using the 'goto' function within the if/else statement. Somehow it does not seem to work out for me. Could you advise weather i have applied the 'goto' correctly please..

Attached is the erroneous section of my code.

for j=1:1:24
for t = 1:1:14
% LABEL noD
no_of_dev = round(rand*500);
current_max_dev = rg_dev_avail(j:t);

if no_of_dev > current_max_dev
goto('noD') % If condition not satisfied goto label noD
return
else
new_rg_dev_list(j:t) = no_of_dev;
end
end
end

Thanks!

Muhammad

% LABEL Start
global j new_pop Best_Solution Zeta_Best_Solution Best_Solution1 Zeta_Best_Solution1;
% Generating 10 population in each generation
global Npop;
Npop=100;
Pop=Iniziatitation_Population(10,Npop);
n=1;
if Zeta_Best_Solution<=0.64;
goto('Start')
end
but I got error messages as follows :
Error using goto (line 638)
Error: Illegal use of reserved keyword "elseif".

Error in mainGA2 (line 85)
goto('Start')

What should I do? Please give me suggestion to use your functions

Regards

Aaron

Aaron (view profile)

This code would be extremely useful because I'd rather not put 2/3 of my very long m-file into an if statement, but unfortunately I hit a problem as I have a continue statement in the section of code that I want to go to using goto. I noticed you mentioned in 2010 that you were thinking of adding in support for continue and break statements... are there any plans to do so?

Lee Loon

I had try the example and its works. However i was facing a problem when applied it in my own program which it come out ''??? Index exceeds matrix dimensions.'' It happen when i use goto(137) in line 335. But it works when i use goto(314) in line 294(another part in same program). Will this mean the goto function not suitable to use for big gap?

Jerry

Jerry (view profile)

Hi I think you miss the situation of following code:

Temp = [1,2,3;
2,3,4;
3,4,5];

In such case, the goto file reports wrong, Perhaps you should add some judgement on '...,' or in complete sentences.

Diego, thank you for the feedback, but why didn't you rate the file accordingly? :-)

You're right about multiple line inputs, I already did it for the more important ones (FOR, WHILE, IF, BREAK, etc...) but from a programming point of view, doing it for multiple lines distinguished by "..." is pretty simple. I guess this is a reason for an update soon.

Glad the file helped, come again!

Diego

Diego (view profile)

How, very good!

I need something exactly like this. In my case, a FOR loop will make my script graceless because the use of cell and text markup in the code.

With your GOTO function, I construct a for loop without identation or a new text markup.

A contribution that I can do to your work is an error that ocurred when my code has construction in more than one line like the following examples:

A = [1, 2, 3, ...
4, 5, 6];

B = [1 2 3
4 5 6];

In these cases, Matlab return that the line is an invalid statement. I guess it do so because your function not treat these statements. You code already do it in FOR, WHILE, IF, etc, statements, only left these others.

Forgime my bad english, I'm from Brazil and not speak english.

Thank you again!
--
Diego da Silva de Medeiros

@nazish,
That's how a proper goto() would work.

If you want the loop to continue iterating, simple use goto() without following it with a return().

E-mail me next time if you have problems before you rate the file.

nazish

nazish (view profile)

this function doesn't work inside for loops and if statements, it appears to me if it executes the function once, the for loop doesn't execute the next iteration :( , I tried many times.

kiran singh

only one

Khan Sadaf

very well done !

FuzzyPanda_

After having written assembly code, goto is one instruction that cannot be missing from any programming languages. Thank you Husam.

MoDu

MoDu (view profile)

Needed this function (really, no other way) for my thesis, it works great so far.

Rob Campbell

Example 1 worked for me...
Vaguely amusing to see this although I must admit that I'm never going to use it.

Oleg, you'll have to excuse my skepticism, but I tried the Example before posting it, it works for all these people, and the error you claimed just doesn't make logical sense.

Here is the specific code snippet:

...
if strcmp(funz{pointer}(1:3),'if ')

cond = evalin('caller',funz{pointer}(3:end)); % <<error here in variable 'pointer'
...

pointer is referenced in the if statement, and the only way the error occurred where you said it did is if the if statement returned true, which cannot have had happened had 'pointer' not been defined in MATLAB's words.

Did you try debugging and finding out why the error occurred? Questions like what does the MATLAB window display before the error (any numbers?), in which recursion the error occurred, which version of MATLAB are you using, etc.

Oleg Komarov

@Husam Aldahiyat
It's a shame you didn't even bother to consider the fact that I am running your example and it doesn't work.

Straigthforward...

@Bruno
I actually had a lot of fun programming/testing this function. And seeing positive response adds to the fun.

@Matt Dunham
Thanks for the fiver! Hope the function helped you.

@claus
I'm glad you found it funny. I guess it is funny imagining MATLAB jump around from line to line, LOL! =]

@Oleg Komarov
It's a shame you don't know how to use a straightforward function with one input.

@Rody Oldenhuis
Thanks for the comment and rating. I think even sloppy messy it just works® code doesn't need goto, but if it helped you or anyone else, then that's certainly good news!

@Malcolm McLean
You can use if true/if false, ctrl+r/ctrl+t, and of course goto :-)

@Cris Luengo
Thanks for the compliment. I think if I invested in more time I could produce a better looking code but I'm glad someone bothered to check out my coding.

Thanks to all the positive response I'll work and submit a better version soon!

Cris Luengo

@Malcom:
You can put an "if 0"/"else"/"end" around the two blocks of code. Flipping the 0 to 1 for the first run, then back to 0 to fiddle with the printout. I do that all the time.

@Rody:
Even with sloppy, quick-n-dirty, messy, one-time-use-only, etc. etc. code, it is much, much, much simpler to use normal flow control than using the GOTO statement. I'm not against the GOTO statement, it wouldn't hurt if MATLAB came with one, but it has very limited uses, mainly in recovering from errors. Actually, considering how well the TRY/CATCH thing works, it might not even be useful there...

Having said that, this submission is well written, and shows some interesting uses of MATLAB functionality. I would never have thought that such a function would be possible.

Shahab

Shahab (view profile)

useful, thanks

Matlab should have a goto.

The reason is that often you want skip code in scratch scripts. Currently the only way to do that is to comment out, which creates its own problems.
e.g. the first hundred lines of the script execute lengthy functions, the last 100 lines print out the results in a nice format. During testing, you want to fiddle about with the printout to make it nicer. So you want to be able to run the analysis once, put the results into the workspace, and then run the formatting code several times, quickly, until you get it right.

Rody Oldenhuis

I can think of at least one really useful application for this: to write sloppy, quick-n-dirty, messy, one-time use only, it just works®, thinking-while-writing, deadline-is-near, just finding something out kind of programming :) I know most people here do that a lot, admit it! So instead of indirectly denying this and ban all functions that help and facilitate this kind of sloppy programming is a bit short-sighted in my opinion.

Of course you're not going to use it in any of your "real" work, stuff that others have to see: 1) the author has given a warning as to why you should not do that, and 2) if you still do it, you'll find out soon enough why GOTO() isn't so great.

To give this submission one star because you think people will use GOTO() in "serious" functions or "teach bad habits" is just not recognizing what this function was really made for (or will likely be used for). To jump straight to your purist programmer's saddle and scream fire and death to GOTO() is just silly.

It's actually a pretty good job for what it is. I give it 4 stars.

Ralf

Ralf (view profile)

Oleg Komarov

This submission doesn't work from two points of view:
- doesn't work in the sense it gives me an error
- teaches bad habit

Consider Example 1.

Running, I get:
??? Error using ==> evalin
Undefined function or variable 'pointer'.

Error in ==> goto at 69
cond = evalin('caller',funz{pointer}(3:end));

Why does it teach bad habit?

a = 5;
a = a - 1;
disp(a)
if a > 0
goto(4)
return
end

Because the following code is much more straightforward than the one before:
a = 5;
while a > 0
a = a - 1;
disp(a)
end

If the objective is to make your code slow and obscure then you can take advantage of this submission, otherways just learn the basic logical statements.

Kamil, the procedure is most definitely not for professional use, but just for fun. And thanks for the feedback, an update is on the way.

Kamil Makiela

I give it 3 because it is the only working goto statement I could find. However the procedure is definitely NOT for a professional use. I tested it with Gewek's algorithm for drawing from truncated normal distribution (re-wrote it from GAUSS). I is way slower than accept-reject drawing even though it shouldn't (and isn't in the case of GAUSS code).
But it is always something new!

BTW: Husam you may want to fix the code a bit. The function lefts files unclosed, eventually leading to an overflow of FIDs (on my computer it usually crushed the simulation after 100-120 draws). I simply pushed fclose('all') before the start of each draw but it would be best to fix within the goto function.

Rizwan Ali

Leo Kay

Leo Kay

Good Job :D Testing it here, Its actually really fast ! Thank you

Lorenzo

berth

berth (view profile)

one of the best Matlab function ever found!
very useful and funny :D
it permits to save a lot of space sometimes in the codes.
thank you HUSAM!!!

Matt Dunham

Comments like Bruno's anger me. The author clearly states that is for 'entertainment' only. I for one will look at this function for ideas on solving related problems. Often efficiency is not a major issue when writing meta tools to analyze code, etc.

NOUR

NOUR (view profile)

Bruno Luong

Even for entertained purpose, a quick look shows a heavy coding with attempt to brute emulation of native Matlab using EVALIN. I bet this is goto is slow, unreliable and a night mare to maintain.

Life is too short for this. I'll make a favor to the author: rate it as 1 star so he does not waste more his time on this goto.

As the examples clearly show, using goto can always be circumvented, but it's pretty fun to test and see.

Also, lines with multiple commands should pose no problem if these lines don't contain a reserved MATLAB word. And if this submission doesn't get bombarded with 1/5 ratings, then I could update it to include support for continue and break statements.

Updates

1.8.0.0

Changed explanation and help.

1.7.0.0

Added ability to jump to a different m file.

1.6.0.0

Added string label support as well as vector/cell input support.

1.5.0.0

Added support for jumping to a label string.

1.3.0.0

Edited some comments.

1.2.0.0

Closed the open fids.

1.1.0.0

Fixed a lot of bugs, made code much more fool-proof, added support for continue and break, added five more examples.

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

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.


Learn About Live Editor