3.95

4.0 | 21 ratings Rate this file 51 Downloads (last 30 days) File Size: 9.21 KB File ID: #26949
image thumbnail

MATLAB Goto Statement

by Husam Aldahiyat

 

14 Mar 2010 (Updated 17 Feb 2011)

The one and only.

| Watch this File

File Information
Description

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

MATLAB release MATLAB 7.5 (R2007b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (31)
15 Mar 2010 Husam Aldahiyat

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.

19 Mar 2010 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.

09 Apr 2010 NOUR  
02 May 2010 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.

14 May 2010 claus

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!!!

28 Jul 2010 Lorenzo  
03 Aug 2010 Leo Kay

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

17 Aug 2010 Leo Kay  
17 Oct 2010 Rizwan Ali  
13 Nov 2010 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.

16 Nov 2010 Husam Aldahiyat

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.

16 Nov 2010 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.

18 Nov 2010 Ralf  
19 Nov 2010 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.

29 Nov 2010 Malcolm McLean

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.

02 Jan 2011 Shahab

useful, thanks

13 Jan 2011 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.

13 Jan 2011 Husam Aldahiyat

@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!

13 Jan 2011 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...

14 Jan 2011 Husam Aldahiyat

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.

16 Feb 2011 Rob Campbell

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

04 Apr 2011 MoDu

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

19 May 2011 FuzzyPanda_

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

23 May 2011 Khan Sadaf

very well done !

08 Sep 2011 bishanka bhowmik  
03 Nov 2011 kiran singh

only one

22 Nov 2011 nazish

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.

22 Nov 2011 Husam Aldahiyat

@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.

07 Mar 2012 Diego

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

07 Mar 2012 Husam Aldahiyat

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!

07 Mar 2012 Jerry

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.

Please login to add a comment or rating.
Updates
19 Mar 2010

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

16 Nov 2010

Closed the open fids.

12 Jan 2011

Edited some comments.

16 Feb 2011

Added support for jumping to a label string.

16 Feb 2011

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

16 Feb 2011

Added ability to jump to a different m file.

17 Feb 2011

Changed explanation and help.

Tag Activity for this File
Tag Applied By Date/Time
goto Husam Aldahiyat 15 Mar 2010 12:40:07
jump Husam Aldahiyat 15 Mar 2010 12:40:07
jmp Husam Aldahiyat 15 Mar 2010 12:40:07
line Husam Aldahiyat 15 Mar 2010 12:40:07
label Husam Aldahiyat 15 Mar 2010 12:40:07
goto Naftali Herscovici 28 Jun 2010 09:35:45
goto Carlo Ventura 24 Jan 2011 17:40:48
nan Husam Aldahiyat 17 Feb 2011 11:24:48
inf Husam Aldahiyat 17 Feb 2011 11:24:48
vectorized Husam Aldahiyat 17 Feb 2011 11:24:48
goto Arun Maari Rajha K V 06 Aug 2011 11:20:24
goto Reza Ghahremaninejad 15 Aug 2011 10:39:58
goto bassel 19 Nov 2011 03:12:24
jump Bill Spoja 24 Apr 2012 20:36:10

Contact us at files@mathworks.com