Thread Subject: How to do GOTO in Matlab

Subject: How to do GOTO in Matlab

From: daniel_nordlund_1982@hotmail.com

Date: 10 Dec, 2006 11:29:44

Message: 1 of 38

I've seen many people on this newsgroup ask for a GOTO statement. Since
such a statement doesn't exist, I've decided to help MathWorks
implement one. Rather than a line number approach, I've based it on
named labels. Here's a fine example of how you can use it:

s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
goto lower(s(1));
m:: goto 'n'+(rand>.5)*11;
y:: fprintf('You are sure\n'), goto 'ok';
n:: fprintf('You are not sure\n')
ok::

Note that labels end with :: and goto statements end with a ;. The
expression in a goto statement is converted to a string and execution
continues at the corresponding label. Illegal label names simply
terminate the program.

To be able to run this code, you must first transform it to valid
Matlab code. Just use the following helper function:

function s=gotofix(g)
f=fopen(g,'rt'); s=char(fread(f)'); fclose(f);
s=sprintf(['IP=pi; while IP try switch IP case pi\n%s IP=[];' ...
' otherwise,IP=[];\nend,catch,[EM IP]=lasterr;if nnz(IP)<2|' ...
'IP(1)*IP(2)-6554\nerror(IP,EM),end,IP(1:2)=[];end,end\n'], ...
regexprep(s,{'(?m)^(.)','([\s,;])goto\s*([^;]+)','(\w+)\s*::' ...
},{' $1','$1error([''q:'' $2],'''')','IP=''$1''; case''$1'','}));

Send the input m-file as an argument and the transformed file will be
returned. The result can be stored to a new m-file or executed
directly:

>> eval(gotofix('areyousure.m'))

For those interested, here's what the transformed version of the
example will look like:

IP=pi; while IP try switch IP case pi
  s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
  error(['q:' lower(s(1))],'');
  IP='m'; case'm', error(['q:' 'n'+(rand>.5)*11],'');
  IP='y'; case'y', fprintf('You are sure\n'), error('q:ok','');
  IP='n'; case'n', fprintf('You are not sure\n')
  IP='ok'; case'ok',
  IP=[]; otherwise,IP=[];
end,catch,[EM IP]=lasterr;if nnz(IP)<2|IP(1)*IP(2)-6554
error(IP,EM),end,IP(1:2)=[];end,end

This technique can be used to make a more versatile goto statement
(work is in progress). Here are some limitations and notes for the
above version of GOTOFIX:
- Only works with scripts, not functions. (Easily fixed.)
- You can use it to jump OUT of for-loops, nested for-loops, if-blocks,
etc, but you can not jump INTO or BETWEEN them. You can fix this by
replacing all for, while, if-blocks, etc in your code with appropriate
GOTO constructs.
- The variables IP and EM are reserved and should not be used in your
code.
- The ASCII code for 'q' is prime. (Why is this important?)

Daniel

Subject: How to do GOTO in Matlab

From: per isakson

Date: 10 Dec, 2006 15:06:35

Message: 2 of 38

daniel_nordlund_1982 wrote:
>
>
> I've seen many people on this newsgroup ask for a GOTO statement.
> Since
> such a statement doesn't exist, I've decided to help MathWorks
> implement one. Rather than a line number approach, I've based it on
> named labels. Here's a fine example of how you can use it:
>
> s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
> goto lower(s(1));
> m:: goto 'n'+(rand>.5)*11;
> y:: fprintf('You are sure\n'), goto 'ok';
> n:: fprintf('You are not sure\n')
> ok::
>
> Note that labels end with :: and goto statements end with a ;. The
> expression in a goto statement is converted to a string and
> execution
> continues at the corresponding label. Illegal label names simply
> terminate the program.
>
> To be able to run this code, you must first transform it to valid
> Matlab code. Just use the following helper function:
>
> function s=gotofix(g)
> f=fopen(g,'rt'); s=char(fread(f)'); fclose(f);
> s=sprintf(['IP=pi; while IP try switch IP case pi\n%s IP=[];' ...
> ' otherwise,IP=[];\nend,catch,[EM IP]=lasterr;if nnz(IP)<2|' ...
> 'IP(1)*IP(2)-6554\nerror(IP,EM),end,IP(1:2)=[];end,end\n'], ...
> regexprep(s,{'(?m)^(.)','([\s,;])goto\s*([^;]+)','(\w+)\s*::' ...
> },{' $1','$1error([''q:'' $2],'''')','IP=''$1''; case''$1'','}));
>
> Send the input m-file as an argument and the transformed file will
> be
> returned. The result can be stored to a new m-file or executed
> directly:
>
>>> eval(gotofix('areyousure.m'))
>
> For those interested, here's what the transformed version of the
> example will look like:
>
> IP=pi; while IP try switch IP case pi
> s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
> error(['q:' lower(s(1))],'');
> IP='m'; case'm', error(['q:' 'n'+(rand>.5)*11],'');
> IP='y'; case'y', fprintf('You are sure\n'), error('q:ok','');
> IP='n'; case'n', fprintf('You are not sure\n')
> IP='ok'; case'ok',
> IP=[]; otherwise,IP=[];
> end,catch,[EM IP]=lasterr;if nnz(IP)<2|IP(1)*IP(2)-6554
> error(IP,EM),end,IP(1:2)=[];end,end
>
> This technique can be used to make a more versatile goto statement
> (work is in progress). Here are some limitations and notes for the
> above version of GOTOFIX:
> - Only works with scripts, not functions. (Easily fixed.)
> - You can use it to jump OUT of for-loops, nested for-loops,
> if-blocks,
> etc, but you can not jump INTO or BETWEEN them. You can fix this by
> replacing all for, while, if-blocks, etc in your code with
> appropriate
> GOTO constructs.
> - The variables IP and EM are reserved and should not be used in
> your
> code.
> - The ASCII code for 'q' is prime. (Why is this important?)
>
> Daniel
>

Mathworks has announced a goto function: "Vectorized goto in MATLAB"
[ <http://blogs.mathworks.com/loren/?cat=1> ].

How does your function compared to Mathwork's plans?

/ per

Subject: How to do GOTO in Matlab

From: Harmonic Software

Date: 15 Dec, 2006 10:59:09

Message: 3 of 38

[This followup was posted to comp.soft-sys.matlab and a copy was sent to
the cited author.]

We implemented labeled gotos in O-Matrix,
http://www.omatrix.com/manual/goto.htm and although this construct needs
to be used judicously it has proven very popular.

In article <ef4839d.0@webcrossing.raydaftYaTP>, poi1@kth2.se says...
> daniel_nordlund_1982 wrote:
> >
> >
> > I've seen many people on this newsgroup ask for a GOTO statement.
> > Since
> > such a statement doesn't exist, I've decided to help MathWorks
> > implement one. Rather than a line number approach, I've based it on
> > named labels. Here's a fine example of how you can use it:
> >
> > s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
> > goto lower(s(1));
> > m:: goto 'n'+(rand>.5)*11;
> > y:: fprintf('You are sure\n'), goto 'ok';
> > n:: fprintf('You are not sure\n')
> > ok::
> >
> > Note that labels end with :: and goto statements end with a ;. The
> > expression in a goto statement is converted to a string and
> > execution
> > continues at the corresponding label. Illegal label names simply
> > terminate the program.
> >
> > To be able to run this code, you must first transform it to valid
> > Matlab code. Just use the following helper function:
> >
> > function s=gotofix(g)
> > f=fopen(g,'rt'); s=char(fread(f)'); fclose(f);
> > s=sprintf(['IP=pi; while IP try switch IP case pi\n%s IP=[];' ...
> > ' otherwise,IP=[];\nend,catch,[EM IP]=lasterr;if nnz(IP)<2|' ...
> > 'IP(1)*IP(2)-6554\nerror(IP,EM),end,IP(1:2)=[];end,end\n'], ...
> > regexprep(s,{'(?m)^(.)','([\s,;])goto\s*([^;]+)','(\w+)\s*::' ...
> > },{' $1','$1error([''q:'' $2],'''')','IP=''$1''; case''$1'','}));
> >
> > Send the input m-file as an argument and the transformed file will
> > be
> > returned. The result can be stored to a new m-file or executed
> > directly:
> >
> >>> eval(gotofix('areyousure.m'))
> >
> > For those interested, here's what the transformed version of the
> > example will look like:
> >
> > IP=pi; while IP try switch IP case pi
> > s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
> > error(['q:' lower(s(1))],'');
> > IP='m'; case'm', error(['q:' 'n'+(rand>.5)*11],'');
> > IP='y'; case'y', fprintf('You are sure\n'), error('q:ok','');
> > IP='n'; case'n', fprintf('You are not sure\n')
> > IP='ok'; case'ok',

Subject: How to do GOTO in Matlab

From: John D'Errico

Date: 15 Dec, 2006 13:20:55

Message: 4 of 38

Harmonic Software wrote:
>
>
> [This followup was posted to comp.soft-sys.matlab and a copy was
> sent to
> the cited author.]
>
> We implemented labeled gotos in O-Matrix,
> <http://www.omatrix.com/manual/goto.htm>
> nd although this construct needs
> to be used judicously it has proven very popular.

I knew there were good reasons NOT
to use O-Matrix.

Just because something is popular
does not make it worthy. Cocaine
is a "popular" drug.

John

Subject: How to do GOTO in Matlab

From: Rune Allnor

Date: 15 Dec, 2006 10:39:40

Message: 5 of 38


per isakson skrev:
> daniel_nordlund_1982 wrote:
> >
> >
> > I've seen many people on this newsgroup ask for a GOTO statement.
> > Since
> > such a statement doesn't exist, I've decided to help MathWorks
> > implement one.

>
> Mathworks has announced a goto function: "Vectorized goto in MATLAB"
> [ <http://blogs.mathworks.com/loren/?cat=1> ].
>
> How does your function compared to Mathwork's plans?

Please, tell me you've delayed your April fool's day pranks till now?

Did it occur to anyone that there might be a reason why GOTO's
don't exist in any high-level programming language designed for
almost half a century?

And this idea presented on the mathworks blog: Instead of using
labels to designate where a GOT jump should land, the LINE
NUMBER of the source code or the CONTENTS of the line
of source code should designate the destination?

Two *tiny* objections come to mind:

1) How would somebody be able to maintain source code integrity
with line numbers as keys for destinations? What happens if
somebody inserts a couple of lines of code or comments after
the GOTO jump has been programmed?

2) What happens if somebody in, say, debugging find that the
contents of the line where the GOTO jump is destined to arrive
needs to change?

If TMW actually implements these modifications, they will
reach the dubious achievemnets of obfuscating GOTO statements
orders of magnitude beyond what even FORTRAN was able to.

Rune

Subject: How to do GOTO in Matlab

From: Steven Lord

Date: 15 Dec, 2006 14:27:26

Message: 6 of 38


<daniel_nordlund_1982@hotmail.com> wrote in message
news:1165778984.266098.310630@73g2000cwn.googlegroups.com...
> I've seen many people on this newsgroup ask for a GOTO statement. Since
> such a statement doesn't exist, I've decided to help MathWorks
> implement one. Rather than a line number approach, I've based it on
> named labels. Here's a fine example of how you can use it:
>
> s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
> goto lower(s(1));
> m:: goto 'n'+(rand>.5)*11;
> y:: fprintf('You are sure\n'), goto 'ok';
> n:: fprintf('You are not sure\n')
> ok::

I would probably implement the above example with a SWITCH statement:


function yn = areyousure
yn = [];
while isempty(yn)
    s = input('Are you sure? (Y)es, (N)o, or (M)aybe:', 's');
    if ~isempty(s)
        switch lower(s(1))
        case 'y'
            yn = true;
        case 'n'
            yn = false;
        case 'm'
            disp('Please decide if you are sure or if you are not.');
        otherwise
            disp('I''m sorry, I didn''t understand your answer.');
        end
    else
        disp('Please choose an answer.');
    end
end


or, if I'm allowed to display a dialog box, like this:


function yn = areyousure2
yn = [];
while isempty(yn)
    ButtonName = questdlg('Are you sure?', 'Confirmation dialog', ...
        'Yes', 'No', 'Maybe', 'Yes');
    switch ButtonName
        case 'Yes'
            yn = true;
        case 'No'
            yn = false;
        case 'Maybe'
            disp('Please decide if you are sure or if you are not.');
    end
end


> Note that labels end with :: and goto statements end with a ;. The
> expression in a goto statement is converted to a string and execution
> continues at the corresponding label. Illegal label names simply
> terminate the program.
>
> To be able to run this code, you must first transform it to valid
> Matlab code. Just use the following helper function:
>
> function s=gotofix(g)
> f=fopen(g,'rt'); s=char(fread(f)'); fclose(f);
> s=sprintf(['IP=pi; while IP try switch IP case pi\n%s IP=[];' ...
> ' otherwise,IP=[];\nend,catch,[EM IP]=lasterr;if nnz(IP)<2|' ...
> 'IP(1)*IP(2)-6554\nerror(IP,EM),end,IP(1:2)=[];end,end\n'], ...
> regexprep(s,{'(?m)^(.)','([\s,;])goto\s*([^;]+)','(\w+)\s*::' ...
> },{' $1','$1error([''q:'' $2],'''')','IP=''$1''; case''$1'','}));
>
> Send the input m-file as an argument and the transformed file will be
> returned. The result can be stored to a new m-file or executed
> directly:
>
>>> eval(gotofix('areyousure.m'))
>
> For those interested, here's what the transformed version of the
> example will look like:
>
> IP=pi; while IP try switch IP case pi
> s=input('Are you sure (Y)es, (N)o, (M)aybe? ','s');
> error(['q:' lower(s(1))],'');
> IP='m'; case'm', error(['q:' 'n'+(rand>.5)*11],'');
> IP='y'; case'y', fprintf('You are sure\n'), error('q:ok','');
> IP='n'; case'n', fprintf('You are not sure\n')
> IP='ok'; case'ok',
> IP=[]; otherwise,IP=[];
> end,catch,[EM IP]=lasterr;if nnz(IP)<2|IP(1)*IP(2)-6554
> error(IP,EM),end,IP(1:2)=[];end,end

In my personal opinion, that code looks much more confusing than the
SWITCH-CASE code. I think it would take me a few minutes of thought to
figure out what it's doing, especially the last two lines, if I had to go
back to it a week, a month, or a year from now.

--
Steve Lord
slord@mathworks.com

Subject: How to do GOTO in Matlab

From: Steven Lord

Date: 15 Dec, 2006 14:33:03

Message: 7 of 38


"Rune Allnor" <allnor@tele.ntnu.no> wrote in message
news:1166207980.367759.127610@t46g2000cwa.googlegroups.com...
>
> per isakson skrev:
>> daniel_nordlund_1982 wrote:
>> >
>> >
>> > I've seen many people on this newsgroup ask for a GOTO statement.
>> > Since
>> > such a statement doesn't exist, I've decided to help MathWorks
>> > implement one.
>
>>
>> Mathworks has announced a goto function: "Vectorized goto in MATLAB"
>> [ <http://blogs.mathworks.com/loren/?cat=1> ].
>>
>> How does your function compared to Mathwork's plans?
>
> Please, tell me you've delayed your April fool's day pranks till now?
>
> Did it occur to anyone that there might be a reason why GOTO's
> don't exist in any high-level programming language designed for
> almost half a century?
>
> And this idea presented on the mathworks blog: Instead of using
> labels to designate where a GOT jump should land, the LINE
> NUMBER of the source code or the CONTENTS of the line
> of source code should designate the destination?

Um, Rune?

Please take a look at when Loren posted that blog entry, and the 3rd, 6th,
and 9th comments on that blog entry.

I'm sure Loren will be pleased that she was able to write an April Fool's
post convincing enough to cause this kind of concern.

Although I do like the idea of goto(NaN) going to a random line. It seems
evil enough to be worthy of NaN :)

*snip*

--
Steve Lord
slord@mathworks.com

Subject: How to do GOTO in Matlab

From: NZTideMan

Date: 15 Dec, 2006 11:50:08

Message: 8 of 38

Could I suggest a minor improvement to Steven's excellent dialog:

function yn = areyousure2
yn = [];
count=0;
while isempty(yn)
    ButtonName = questdlg('Are you sure?', 'Confirmation dialog', ...
        'Yes', 'No', 'Maybe', 'Yes');
    switch ButtonName
        case 'Yes'
            yn = true;
        case 'No'
            yn = false;
        case 'Maybe'
            Count=Count + 1;
             if Count < 3
                       disp('Please decide if you are sure or if you
are not.');
              else
                      disp('Stop dithering and decide one way or the
other');
             endif
    end
end

Subject: How to do GOTO in Matlab

From: NZTideMan

Date: 15 Dec, 2006 11:52:29

Message: 9 of 38


> if Count < 3
> disp('Please decide if you are sure or if you
> are not.');
> else
> disp('Stop dithering and decide one way or the
> other');
> endif


Oooops. See who's been writing Fortran recently?

Subject: How to do GOTO in Matlab

From: Rune Allnor

Date: 15 Dec, 2006 12:07:54

Message: 10 of 38


Steven Lord skrev:
> "Rune Allnor" <allnor@tele.ntnu.no> wrote in message
> news:1166207980.367759.127610@t46g2000cwa.googlegroups.com...
> >
> > per isakson skrev:
> >> daniel_nordlund_1982 wrote:
> >> >
> >> >
> >> > I've seen many people on this newsgroup ask for a GOTO statement.
> >> > Since
> >> > such a statement doesn't exist, I've decided to help MathWorks
> >> > implement one.
> >
> >>
> >> Mathworks has announced a goto function: "Vectorized goto in MATLAB"
> >> [ <http://blogs.mathworks.com/loren/?cat=1> ].
> >>
> >> How does your function compared to Mathwork's plans?
> >
> > Please, tell me you've delayed your April fool's day pranks till now?
> >
> > Did it occur to anyone that there might be a reason why GOTO's
> > don't exist in any high-level programming language designed for
> > almost half a century?
> >
> > And this idea presented on the mathworks blog: Instead of using
> > labels to designate where a GOT jump should land, the LINE
> > NUMBER of the source code or the CONTENTS of the line
> > of source code should designate the destination?
>
> Um, Rune?
>
> Please take a look at when Loren posted that blog entry, and the 3rd, 6th,
> and 9th comments on that blog entry.

It WAS an April's fools day prank? OK, you people got me...
It might be a good idea to remove those sorts of stories
after April 1st.

> I'm sure Loren will be pleased that she was able to write an April Fool's
> post convincing enough to cause this kind of concern.

My congratulations to her.

> Although I do like the idea of goto(NaN) going to a random line. It seems
> evil enough to be worthy of NaN :)

Sure. I have seen too much nonsense being proposed in
earnest to think of jokes or sarcasms. As one of the
regulars here repeatedly remind us: "Never attribute to
malice that which can be adequately explained by
stupidity."

Unfortunately, it is an advice I have learned to live by.

Rune

Subject: How to do GOTO in Matlab

From: Go To

Date: 15 Dec, 2006 15:12:27

Message: 11 of 38

The number of (negative) reactions raised every time the
GOTO issue resurfaces is a clear evidence of the bad
conscience of those who deny its utility.

Subject: How to do GOTO in Matlab

From: Peter Boettcher

Date: 15 Dec, 2006 16:36:21

Message: 12 of 38

"Go To" <yours@goooo.too> writes:

> The number of (negative) reactions raised every time the
> GOTO issue resurfaces is a clear evidence of the bad
> conscience of those who deny its utility.

What?

--
Peter Boettcher <boettcher@ll.mit.edu>
MIT Lincoln Laboratory
MATLAB FAQ: http://www.mit.edu/~pwb/cssm/

Subject: How to do GOTO in Matlab

From: NZTideMan

Date: 15 Dec, 2006 17:29:26

Message: 13 of 38


>
> > The number of (negative) reactions raised every time the
> > GOTO issue resurfaces is a clear evidence of the bad
> > conscience of those who deny its utility.

No, you're wrong there.
It's not my conscience at all.
It's bitter experience.
About 15 years ago I was given a Fortran 4 code that was about 2,000
lines long, with not one comment line - I was told: comments are for
quiche-eaters, real programmers don't need them. The code was full of
GOTO's and computed GOTO's, with branches from the middle of the code
to the top, then back down to 3/4 way through, etc, etc. The technical
name for this is "spaghetti code", which is a very apt description.
Unravelling all those strands took me weeks and convinced me of the
need to improve my own programming ways. As a result, I have never
used a GOTO since, and will never do so. And actually, with properly
structured code, there is no need to, ever.

So, Mr GOTO, I attribute your advocacy/need for GOTO's to be a
demonstration of your lack of code-writing skills. Improve those
skills and you won't need GOTO's.

Subject: How to do GOTO in Matlab

From: Go To

Date: 15 Dec, 2006 21:32:49

Message: 14 of 38

> So, Mr GOTO, I attribute your advocacy/need for GOTO's to be a
> demonstration of your lack of code-writing skills. Improve those
> skills and you won't need GOTO's.

Assume whatever you want. Anti GOTOs people, no matter
how hard they try to impose themselfs, they are not
owners of the truth.

P.S. And neither of the programing skills

Subject: How to do GOTO in Matlab

From: Duane Hanselman

Date: 16 Dec, 2006 09:46:47

Message: 15 of 38

Go To wrote:
>
>
>> So, Mr GOTO, I attribute your advocacy/need for GOTO's to be a
>> demonstration of your lack of code-writing skills. Improve
those
>> skills and you won't need GOTO's.
>
> Assume whatever you want. Anti GOTOs people, no matter
> how hard they try to impose themselfs, they are not
> owners of the truth.
>
> P.S. And neither of the programing skills
  
The dialog reminds be of the oxymoron "religious tolerance".
Religious INtolerance appears when parties disagree about truth and
who owns it.

I personally have trouble with truth being absolute or universal. I
find it easier to live with unanswered questions rather than
unquestioned answers.

The path this thread has taken is interesting to me.

Duane

Subject: How to do GOTO in Matlab

From: Roger Stafford

Date: 16 Dec, 2006 15:22:06

Message: 16 of 38

I cannot resist entering into this thread's discussion about go-tos.
My own roots in the world of programming go back well over a half
century, and this argument about the advisability of go-tos dates
back not much more recently than that. However, it has always seemed
to me that such discussions tend to be polarized to two opposite and
somewhat extreme points of view which seem not to admit of other
possibilities.

  On the one hand, my opinion is that the undisciplined use of the
go-to device can indeed lead to very confusing programming which well
deserves the term "spaghetti code". I have experienced enough of
this sort of thing to easily last me a life time (or what little
there is left of it.) When a programmer jumps from one code location
to another distant one without any particular structure present,
someone else trying later to understand this program may not even be
aware for a long time that an entry has been made to this second
location from so far away. There is nothing in such a programming
language that easily gives a clue to this except for the presence of
go-to labels. What a person studying the code really needs at this
point are some "come-from" pointers.

  However, I also hold the view that, too often, the limited
constructs that are made available in the more modern higher
languages are dictated by what is convenient for those who devise
compilers for the languages, as opposed to the needs of programmers
themselves. The pendulum has swung too far to the opposite extreme
in my opinion. I am also aware of the long standing dream of those
whose devise computer languages of trying to enable automatic
analysis of programs written in the language, though this has
apparently not yet really been achieved. Presumably, the simpler the
constructs used, the more likely such analyses could be made
automatic.

  For me, living with the existing constructs in languages such as
Pascal, C, and others like them, has always seemed like being tightly
boxed in with restrictions which made life much more difficult as a
programmer. The claim is often made by defenders of these limited
structures that anything a programmer could possibly wish to code
could always be realized within these structures, but this argument
misses the essential point. They may be needlessly awkward to
achieve within those limitations.

  I will give only one example of the sort of thing I have in mind
here. Suppose at a point in a program there is a decision to be made
of the "if" kind. If such-and-such is true, do A, otherwise go do B.
 Next suppose after doing A we reach another decision point where we
can go either to do task C or task D. Also, after doing B, the
program needs to do either the same task C or task E. After C, D,
and E, these lines can then join together again for further action.
Further, let us suppose this common task C is sufficiently extensive
that we don't really want to have to write duplicate coding for it,
and yet we are reluctant to have to write C as a separate function to
be called upon, since that would tend to interrupt the natural flow
of programming thought. Unfortunately, the higher languages I am
aware of do not permit this very simple action to be achieved easily
and directly, even though the concept of such a flow is easy to
envision in the human mind. A kindergarten pupil can readily grasp
the idea. Of course with Boolean manipulations the net effect can be
achieved, but this would be an artifice and not in accordance with
the way minds tend to think (even minds as weird as those of us
computer programmers.)

  The task of translating a complex set of programming notions into a
linear set of program language sentences places a great strain on
human capabilities. I contend that our minds do not easily think in
this linear fashion. We can envision actions depicted on a
two-dimensional flow chart far more easily and quickly than with a
linear sequence of sentences. Perhaps someday far off in the future
when technology permits, all programs will be constructed on two- and
three-dimensional media that call more effectively upon human
comprehension of spatial relationships. But, until such a thing
becomes possible, it would behoove designers of higher languages to
continually strive for a more richly varied set of structures for
programmers to use, while at the same time, of course, guarding
against the chaos of spaghetti coding.

Roger Stafford

Subject: How to do GOTO in Matlab

From: Bjorn Gustavsson

Date: 17 Dec, 2006 02:41:30

Message: 17 of 38

Go To wrote:
>
>
> The number of (negative) reactions raised every time the
> GOTO issue resurfaces is a clear evidence of the bad
> conscience of those who deny its utility.
>
But goto is so 1960s. Nowadays there are far more powerful constructs
for creating program flow...

...what I would like to see in matlab is some of the funnier
constructs from occam: par, channel arrays, process replicator...

Bjorn

Subject: How to do GOTO in Matlab

From: Jan Houska

Date: 18 Dec, 2006 08:38:48

Message: 18 of 38

Hi,

Roger Stafford wrote:
<snip>

> I will give only one example of the sort of thing I have in mind
> here. Suppose at a point in a program there is a decision to be made
> of the "if" kind. If such-and-such is true, do A, otherwise go do B.
> Next suppose after doing A we reach another decision point where we
> can go either to do task C or task D. Also, after doing B, the
> program needs to do either the same task C or task E. After C, D,
> and E, these lines can then join together again for further action.
> Further, let us suppose this common task C is sufficiently extensive
> that we don't really want to have to write duplicate coding for it,
> and yet we are reluctant to have to write C as a separate function to
> be called upon, since that would tend to interrupt the natural flow
> of programming thought. Unfortunately, the higher languages I am
> aware of do not permit this very simple action to be achieved easily
> and directly, even though the concept of such a flow is easy to
> envision in the human mind. A kindergarten pupil can readily grasp
> the idea. Of course with Boolean manipulations the net effect can be
> achieved, but this would be an artifice and not in accordance with
> the way minds tend to think (even minds as weird as those of us
> computer programmers.)

<snip>

If the common task C is sufficiently extensive, write a function for it.
I don't see how a function, when designed properly, can "interrupt the
natural flow of programming thought". It rather encapsulates that common
task and gives it a name and an interface, in effect simplifying the
code and making it easier to read.

Whenever one is tempted to use goto, he/she should consider if/switch or
a loop (possibly with break) first. If this doesn't fit the pattern and
"goto is really needed in this particular case", then a separate
function or try/catch is usually needed instead. I have never seen a
program in a modern programming language (like C++) where goto improves
code readability. The rule "goto in code == poorly designed code" seems
to have no exceptions.


Just my $0.02.

Jan

--
Jan Houska HUMUSOFT s.r.o.
houska@humusoft.com Pobrezni 20
http://www.humusoft.com 186 00 Praha 8
tel: ++ 420 284 011 730 Czech Republic
fax: ++ 420 284 011 740

Subject: How to do GOTO in Matlab

From: ArthurDoodson@gmail.com

Date: 18 Dec, 2006 01:22:40

Message: 19 of 38


Jan, I agree entirely.
What a load of tripe from that Stafford fellow!!
Can you imagine what his code must look like if he doesn't use a
function to do things that are executed more than once?
And he thinks by not using functions his code flows better and is more
readable?
What planet does this guy live on?
He says he's been programming for more than 50 years. That makes him
well over 65, I reckon.
Time he retired, IMHO.

Subject: How to do GOTO in Matlab

From: Adrian Cherry

Date: 18 Dec, 2006 10:26:51

Message: 20 of 38

"Duane Hanselman" <masteringmatlab@yahoo.com> wrote in
news:ef4839d.13@webcrossing.raydaftYaTP:
>
> The dialog reminds be of the oxymoron "religious tolerance".
> Religious INtolerance appears when parties disagree about
> truth and who owns it.
>
> I personally have trouble with truth being absolute or
> universal. I find it easier to live with unanswered
> questions rather than unquestioned answers.
>
> The path this thread has taken is interesting to me.
>
> Duane


There is a interesting and quite balanced view on the use of goto
from Steve McConnell in "Code Complete"

www.stevemcconnell.com/ccgoto.htm

As he points out one of the most engineered languages ada has
included the goto construct so presumably they saw some merit in
it's use.

Apologies for picking up on your post in this thread, I felt
safer avoiding the anti goto zealots!

Regards

Adrian Cherry

Subject: How to do GOTO in Matlab

From: Steve Amphlett

Date: 18 Dec, 2006 05:55:01

Message: 21 of 38

Adrian Cherry wrote:
>
>
> There is a interesting and quite balanced view on the use of goto
> from Steve McConnell in "Code Complete"
>
> www.stevemcconnell.com/ccgoto.htm
>
> As he points out one of the most engineered languages ada has
> included the goto construct so presumably they saw some merit in
> it's use.

As of course does C (and therefore C++), although I can't say I've
ever used it (unlike my old friend: longjmp). Still, it's always
nice to know that there is a "get out of jail free" card for when the
unforseen finally bites.

Subject: How to do GOTO in Matlab

From: Go To

Date: 18 Dec, 2006 09:18:32

Message: 22 of 38

Jan Houska wrote:

> Whenever one is tempted to use goto, he/she should consider
> if/switch or
> a loop (possibly with break) first. If this doesn't fit the pattern
> and
> "goto is really needed in this particular case", then a separate
> function or try/catch is usually needed instead. I have never seen
> a
> program in a modern programming language (like C++) where goto
> improves
> code readability. The rule "goto in code == poorly designed code"
> seems
> to have no exceptions.

This is a classical example of what I mean.
The guy is absolutely sure that "one is tempted
to use a goto" you should not do it.
And one should not do it because:
1. There are other options
2. The code will forcedly be "poorly designed"

The really irritating part in this kind of reasoning is
that it forgets that if I want to screw up my code,
it is MY code and I don't have to accept any
moral pseudo-superiority of who states so.

ArthurDoodson wrote:

> He says he's been programming for more than 50 years.
> That makes him
> well over 65, I reckon.
> Time he retired, IMHO.

If you are alive now, chances are good that you will also
be 65 one day. Though, judging for its current state,
it won't be much left from your intellect.

Subject: How to do GOTO in Matlab

From: Steve Amphlett

Date: 18 Dec, 2006 09:27:39

Message: 23 of 38

Go To wrote:
>
>
> This is a classical example of what I mean.
> The guy is absolutely sure that "one is tempted
> to use a goto" you should not do it.
> And one should not do it because:
> 1. There are other options
> 2. The code will forcedly be "poorly designed"
>
> The really irritating part in this kind of reasoning is
> that it forgets that if I want to screw up my code,
> it is MY code and I don't have to accept any
> moral pseudo-superiority of who states so.

Though not normally one for flame wars, this cannot go unreplied.
The assumption that "it is MY code" is only true if you are a
hobbiest or student. Real code generally outlives the original
developer and has to be maintained, extended or re-implemented later
on by someone who needs to understand it.

Similarly, unless you are writing the code for fun, it probably
belongs to your employer - the people who pay for the hardware and
software used to develop it, plus your time spent screwing it up.

Subject: How to do GOTO in Matlab

From: Duane Hanselman

Date: 18 Dec, 2006 09:28:54

Message: 24 of 38

Go To wrote:

>
> This is a classical example of what I mean.
> The guy is absolutely sure that "one is tempted
> to use a goto" you should not do it.
> And one should not do it because:
> 1. There are other options
> 2. The code will forcedly be "poorly designed"
>
> The really irritating part in this kind of reasoning is
> that it forgets that if I want to screw up my code,
> it is MY code and I don't have to accept any
> moral pseudo-superiority of who states so.
>
> ArthurDoodson wrote:
>
>> He says he's been programming for more than 50 years.
>> That makes him
>> well over 65, I reckon.
>> Time he retired, IMHO.
>
> If you are alive now, chances are good that you will also
> be 65 one day. Though, judging for its current state,
> it won't be much left from your intellect.

I don't understand the need for disrespectful dialog about this issue.

Subject: How to do GOTO in Matlab

From: Adrian Cherry

Date: 18 Dec, 2006 14:32:28

Message: 25 of 38

"Duane Hanselman" <masteringmatlab@yahoo.com> wrote in
news:ef4839d.22@webcrossing.raydaftYaTP:

> I don't understand the need for disrespectful dialog about
> this issue.
>

The voice of reason - goto the top of the class <g>

Regards

Adrian

Subject: How to do GOTO in Matlab

From: Rune Allnor

Date: 18 Dec, 2006 07:08:53

Message: 26 of 38


Go To skrev:
> if I want to screw up my code,
> it is MY code

What you do with your own code is your own business.
What you do with code you are paid to make or maintain, is
a completely different issue. There are three time scales that
are interesting with computer code:

1) First implementation
2) Run-time
3) Code maintenance

Lots of people are aware of the time it takes from project start-up
to a first running version of the program is available. Some are
even aware of factors that affect the run-time of the program.
Almost no one are aware of code maintenance as a
time/cost issue.

To "maintain computer code" means that one corrects bugs
that are discovered post release, and that one includes
new features in follow-up releases of the program.
A well-designed program reduces maintenance time at the
expense of time for first implementation, and even to some
extent, run-time. Spaghetti code obfuscates program
structure, and is therefore counter-productive what code
maintenance is concerned.

I just spent a couple of days this weekend to track down a
bug in a program I made one year ago. It was my own
code, I made it on my own time with no connections
whatsoever to any paid work. The code performed a task
that is very familiar to me, I did not need to read up on
algorithms or general program structure. The code was
also documented quite well, by my standards. The code
is clearly structured, with different secitons being responsible
for clearly defined tasks. Lots of "expensive" function calls
(well, method calls, this was object oriented C++), no spaghetti.

Even with ana almost ideal starting point, I spent something
like 12 hours over three days, tracking down two bugs. Without
the clear structure of the code I would easily have spent ten
or 20 times as long. Not to mention that with more naive ways
of structuring the code, I might have had to correct some
15-20 instances of the same bug in various files. Because
of OO iheritance I only had to track down and correct one
instance of each bug.

And this is where clearly structured source code shows
its value: Code maintenance time is decreased. No one
want to spend more time than absolutely necessary
on tracking down bugs in old code, be it one's own or
others. That's THE reason why one wants to avoid GOTO.

Rune

Subject: How to do GOTO in Matlab

From: Scott Seidman

Date: 18 Dec, 2006 15:21:46

Message: 27 of 38

"Rune Allnor" <allnor@tele.ntnu.no> wrote in news:1166454533.052735.246280@
73g2000cwn.googlegroups.com:

> Even with ana almost ideal starting point, I spent something
> like 12 hours over three days, tracking down two bugs. Without
> the clear structure of the code I would easily have spent ten
> or 20 times as long.


The best I've ever seen good structure and commenting stressed is that you
should program as if two people need to understand the code: Yourself, and
yourself four weeks later!

--
Scott
Reverse name to reply

Subject: How to do GOTO in Matlab

From: Steven Lord

Date: 18 Dec, 2006 11:35:40

Message: 28 of 38


"Go To" <yours@goooo.too> wrote in message
news:ef4839d.20@webcrossing.raydaftYaTP...
> Jan Houska wrote:
>
>> Whenever one is tempted to use goto, he/she should consider
>> if/switch or
>> a loop (possibly with break) first. If this doesn't fit the pattern
>> and
>> "goto is really needed in this particular case", then a separate
>> function or try/catch is usually needed instead. I have never seen
>> a
>> program in a modern programming language (like C++) where goto
>> improves
>> code readability. The rule "goto in code == poorly designed code"
>> seems
>> to have no exceptions.
>
> This is a classical example of what I mean.
> The guy is absolutely sure that "one is tempted
> to use a goto" you should not do it.
> And one should not do it because:
> 1. There are other options
> 2. The code will forcedly be "poorly designed"
>
> The really irritating part in this kind of reasoning is
> that it forgets that if I want to screw up my code,
> it is MY code and I don't have to accept any
> moral pseudo-superiority of who states so.

I've stayed out of this until now, but there are some very good reasons why
I would be opposed to including GOTO in MATLAB that go beyond the question
of whether or not code would be "poorly designed". Let's assume that we
were to introduce a pair of functions, GOTO and LABEL. GOTO(X) passes
execution to the next instruction after an instance of LABEL(X) in the code,
where X is an explicit string.

Example 1:

% Begin foo.m
function foo
x = 1;
goto('jump1')

function bar(x)
label('jump1')
disp(x)
% End foo.m

In this example:

1) Assume I've set a breakpoint on the DISP line in the subfunction BAR. I
call FOO. When I enter into debug mode, I type "dbstack" to see in which
function's scope I'm currently located. Which function's scope does it say
I'm in? Am I in function FOO (since I never invoked function BAR) or am I
in function BAR (since the line of code I'm currently on is in function
BAR)?

2) Related to question 1, what gets displayed by the DISP statement? Does
it display 1, since that's the value of x in FOO's workspace and that
workspace "carries over" or does it throw an error, since BAR was not called
and so it can't have had an input argument?

I have a pretty good idea of the solution you're going to propose to avoid
this; don't allow jumping from one function into another. Even that breaks
down in two ways:

Example 2:

% Begin foo.m
function foo
n = 1;
goto('jump1')

    function bar(x)
    label('jump1')
    disp(n+x)
    end
end
% End foo.m

Function BAR is a nested function, nested inside function FOO, and so
technically the LABEL statement inside BAR is also inside function FOO, but
we still have the ambiguity about the value of x.

Example 3:

% Begin foo.m
function foo
x = 1;
goto('jump2')
extra1;
extra2;
% End foo.m

Is the GOTO in this statement a syntax error, since it has no corresponding
LABEL? Maybe, and maybe not. It depends on whether extra1 or extra2 (or
both) are script files containing the associated LABEL('jump2') statement.
If one of extra1 or extra2 are script files with that label, we should be
okay and the GOTO should jump to that label ... if both are script files
with that label, we have an ambiguity and so should error. Even that could
probably be detected. But now I'm going to add in something else evil:

Example 4:

% Begin foo.m
function foo
scriptname = input('Enter the name of a script file to execute: ', 's');
eval(scriptname);
goto('labelInEvaluatedScript');
% End foo.m

If the script file whose name I enter at the input prompt contains the label
labelInEvaluatedScript, should this error or not?

These are just four of the first examples I can see where ambiguity or
undesired behavior occurs due to a GOTO-type operation; if you gave me a
little more time I could come up with others. There are other techniques
you can use to accomplish many of the same goals as a GOTO that don't run
into these issues or ambiguities. In addition, even if we were to add in
GOTO with the intention of it being used in situations where it's
appropriate to do so, it won't be limited to situations where it's
appropriate to do so. [See EVAL.] Introducing a GOTO statement would cause
these problems and it would be too easy to misuse, and for those reasons I
don't think it should be included in the language.

--
Steve Lord
slord@mathworks.com

Subject: How to do GOTO in Matlab

From: ellieandrogerxyzzy@mindspring.com.invalid (Roger Stafford)

Date: 18 Dec, 2006 17:36:10

Message: 29 of 38

  People! People! Let's not turn this into a flame war. We can very
well do without that on CSSM, particularly because on this thread we are
all pretty much limited to whatever language The MathWorks, Inc. has made
available to its matlab users. Neither we nor probably TMW itself are in
a position to have a very profound impact on what philosophy is followed
in higher language construction in the computing world as a whole.

  But we can all dream! We can look to the future and envision how higher
language programming might be made less awkward than it is today. We
users are at least entitled to do that. That is what I tried to do in
that previous article. I suspect that in the not-too-distant future,
computer programmers will look back on this present era of programs based
on a single linear thread of statements, proceeding from a beginning to an
end, with a great deal of disdain. They may say things like, "those poor
people back then did not know how to make full use of their natural human
faculties for two and three dimensional thinking. They had no concept for
width or depth. They could only crawl painfully along a straight line!"
Of course that would be somewhat unfair. What we lack today are the
necessary technological tools for interacting with computers except in
very limited ways. Can you imagine trying to play a computer-simulated
violin via a mouse and keyboard? We cannot yet wave our hands in front of
a computing device in some three dimensional pattern and produce a
complicated program of action, as Klaatu did in the famous movie, "The Day
the Earth Stood Still." It is my opinion that this limitation has
profoundly influenced and restricted the design of our higher languages,
but I do not believe that programmers will forever be limited to just
keyboards, mice, and long sequences of sentences.

  However, coming back to the real, present-day world, I am also entitled
to express an opinion regarding the limitations that are present in the
control structures of most modern higher languages, even given our
primitive interactive methods. As I mentioned earlier, programming in
them has always given me the feeling of being in a straight jacket. In
laying out any fairly complicated algorithm I was continually confronted
with limitations in the language. Overcoming them often took more effort
than the intricacies of the algorithm itself. I have always had the
distinct feeling that things shouldn't have to be that complicated for
simple concepts. Language structures should be there to facilitate a
programmer's ideas, not put up barriers to their realization. I am loath
to give any more examples here for fear of how they may be received by the
people in disagreement with these notions on this issue, but these are
things that have occurred over and over during my long life of
programming. It is my opinion that, generally speaking, any structure one
could diagram on a blackboard in a way that a kindergartner could easily
grasp, is one that ought to be permitted for programmers of a higher
language. Until they pass that test, I personally will not be content
with the status quo.

  Having said that, it may come as a comfort to some of the worried
readers of this thread that in practice I always did knuckle down, abiding
by the accepted rules of higher language, and not use gotos. In fact as I
stated earlier, it is my opinion that the use of a free, undisciplined
goto is to descend into utter chaos, as many of us programmers know from
past experiences in trying to decipher others' or even our own codings. I
once did extensive assembly language coding where there are no structural
restrictions at all, and if higher languages can look complicated, one
should see how convoluted assembly language programming can become in the
wrong hands, particularly when it is used to modify itself. It is in this
latter that obfuscation assumes its ultimate form!

  One of you on this thread has expressed the wish that a person with the
above kind of opinions would hopefully be retiring soon. To that person I
give the comforting reassurance that I have in fact long since retired and
am now an octogenarian (with one foot in the grave and the other on the
proverbial banana peel.) The only harm I can do to the programming world
now lies in whatever wayward advice I may give from time to time to others
in this newsgroup.

Roger Stafford

Subject: How to do GOTO in Matlab

From: Steve Amphlett

Date: 18 Dec, 2006 12:47:15

Message: 30 of 38

Roger Stafford wrote:
>
>
> One of you on this thread has expressed the wish that a person
> with the
> above kind of opinions would hopefully be retiring soon. To that
> person I
> give the comforting reassurance that I have in fact long since
> retired and
> am now an octogenarian (with one foot in the grave and the other on
> the
> proverbial banana peel.) The only harm I can do to the programming
> world
> now lies in whatever wayward advice I may give from time to time to
> others
> in this newsgroup.

How can any of us wage-slaves compete? I have often wondered. I
don't even have enough spare time to read and digest all of Roger's
information-laden posts.

Subject: How to do GOTO in Matlab

From: daniel_nordlund_1982@hotmail.com

Date: 18 Dec, 2006 10:10:23

Message: 31 of 38


Randy Poe skrev:
> I really "needed" a GOTO to handle something I was working
> on over the last few weeks, that required under some conditions
> breaking out of a deeply nested set of loops.
>
> I solved it with a TRY... CATCH structure. Nice thing about
> that is that you can put message and identifier information
> in the condition that you throw. Thus your CATCH block
> can figure out what happened to cause it to trigger, and
> respond appropriately.
>
> One annoyance is that I was also trapping ordinary
> Matlab errors such as syntax errors, so when single-
> stepping through my code, I'd suddenly find myself
> unexpectedly in the CATCH block without an error
> message telling me why. I solved this by having the
> CATCH block echo the LASTERROR output under those
> circumstances.

Yep, that's exactly how I solved it too (see the code in the original
post).

Daniel

Subject: How to do GOTO in Matlab

From: Rune Allnor

Date: 18 Dec, 2006 10:45:29

Message: 32 of 38


Roger Stafford skrev:
> It is my opinion that, generally speaking, any structure one
> could diagram on a blackboard in a way that a kindergartner could easily
> grasp, is one that ought to be permitted for programmers of a higher
> language. Until they pass that test, I personally will not be content
> with the status quo.

The more I learn about maths (or maybe the more I understand
about the maths I know?), the simpler the general ideas
become. Vector spaces, which is the basis for linear algebra,
can be explained -- at least rudimentary -- to high-school kids.
However, the simpler the ideas, the more complicated the
details of algebra, proofs, equivalent forms etc become. It is
one thing to know that eigenvectors exist and what their
properties are. It is quite another to implement a program
from scratch that does the computations.

Rune

Subject: How to do GOTO in Matlab

From: Loren Shure

Date: 18 Dec, 2006 15:11:16

Message: 33 of 38

In article <1166465423.912176.148160@j72g2000cwa.googlegroups.com>,
daniel_nordlund_1982@hotmail.com says...
>
> Randy Poe skrev:
> > I really "needed" a GOTO to handle something I was working
> > on over the last few weeks, that required under some conditions
> > breaking out of a deeply nested set of loops.
> >
> > I solved it with a TRY... CATCH structure. Nice thing about
> > that is that you can put message and identifier information
> > in the condition that you throw. Thus your CATCH block
> > can figure out what happened to cause it to trigger, and
> > respond appropriately.
> >
> > One annoyance is that I was also trapping ordinary
> > Matlab errors such as syntax errors, so when single-
> > stepping through my code, I'd suddenly find myself
> > unexpectedly in the CATCH block without an error
> > message telling me why. I solved this by having the
> > CATCH block echo the LASTERROR output under those
> > circumstances.
>
> Yep, that's exactly how I solved it too (see the code in the original
> post).
>
> Daniel
>
>

Do you know about the options for dbstop w.r.t. errors, specifically:

dbstop if error
dbstop if caught error
dbstop if warning

--Loren
http://blogs.mathworks.com/loren/

Subject: How to do GOTO in Matlab

From: Jan Houska

Date: 19 Dec, 2006 09:11:09

Message: 34 of 38

Go To wrote:
> Jan Houska wrote:
>
>
>>Whenever one is tempted to use goto, he/she should consider
>>if/switch or
>>a loop (possibly with break) first. If this doesn't fit the pattern
>>and
>>"goto is really needed in this particular case", then a separate
>>function or try/catch is usually needed instead. I have never seen
>>a
>>program in a modern programming language (like C++) where goto
>>improves
>>code readability. The rule "goto in code == poorly designed code"
>>seems
>>to have no exceptions.
>
>
> This is a classical example of what I mean.
> The guy is absolutely sure that "one is tempted
> to use a goto" you should not do it.
> And one should not do it because:
> 1. There are other options
> 2. The code will forcedly be "poorly designed"

No, I'm not absolutely sure. I've even used words like "consider",
"usually", "seems", to express that uncertainty. However I have really
never seen a counter-example to what I've said above.

> The really irritating part in this kind of reasoning is
> that it forgets that if I want to screw up my code,
> it is MY code and I don't have to accept any
> moral pseudo-superiority of who states so.

Well, I don't know why the irritation when we basically agree. I just
wrote under the assumption that you don't want to screw up your code. If
you want, feel free to do so. But then please don't be surprised that
people will consider your code screwed up. Some people even prefer not
to work with programmers with this attitude to writing code - and this
may result in problems if those people are your managers.

And, for the purpose of screwing up your code, you don't really need
"goto" in MATLAB. A couple of carefully laid "eval", "evalin" and
"global" would do miracles.

Good Luck, Jan

--
Jan Houska HUMUSOFT s.r.o.
houska@humusoft.com Pobrezni 20
http://www.humusoft.com 186 00 Praha 8
tel: ++ 420 284 011 730 Czech Republic
fax: ++ 420 284 011 740

Subject: How to do GOTO in Matlab

From: Theodore Van Rooy

Date: 20 Dec, 2006 16:00:14

Message: 35 of 38

This has been one of the most interesting reads of my day!

I've been reading this and just laughing... it's just so funny! I
didn't think anyone could actually want GOTO. I haven't been
programming on a professional basis for more than 10 years, so you
must forgive my youngness, but seriously? If you can't accomplish
your program with FOR, SWITCH-CASE, TRY-CATCH and
functions/methods...try a little harder.

I love matlab scripting and i program in Action Script also...Matlab
script is my favorite though :-)

Subject: How to do GOTO in Matlab

From: Peter Boettcher

Date: 20 Dec, 2006 16:38:40

Message: 36 of 38

"Theodore Van Rooy" <munkey906@gmail.com> writes:

> This has been one of the most interesting reads of my day!
>
> I've been reading this and just laughing... it's just so funny! I
> didn't think anyone could actually want GOTO. I haven't been
> programming on a professional basis for more than 10 years, so you
> must forgive my youngness, but seriously? If you can't accomplish
> your program with FOR, SWITCH-CASE, TRY-CATCH and
> functions/methods...try a little harder.

That's exactly the point. Anyone can accomplish the program with the
structures you mention, but there are some types of control flow that
are most easily accomplished with a GOTO structure. It is easy to
abuse, which is why C programmers are urged to avoid it. 99 times out
of 100, if a new C programmer wants to use a GOTO, it is for lack of
understanding the higher-level language elements. But the last 1
might actually be a good idea.

In the Linux kernel community, for instance, the use of goto is
encouraged in certain situations. Why? Because it most naturally
expresses the control flow in those situations. In those situations
the code becomes easier to read and maintain, it maps well onto
hardware, so it's fast. There's just no downside except for leading
newbie programmers into trouble. And they probably shouldn't be
reading kernel code anyway.

The implications of adding GOTO to MATLAB are a different story. The
ill effects on the whole package would overpower any small coding
gains.

Debate the topic if you want to, but can we please move a little
further from the creed that says "Gotos must never be used because
they lead to spaghetti code?". It's a great starting point, but not
the end of the debate. See previous conversations here about global
variables for instance. Good to avoid? Absolutely. Often quite
useful? Yep.


--
Peter Boettcher <boettcher@ll.mit.edu>
MIT Lincoln Laboratory
MATLAB FAQ: http://www.mit.edu/~pwb/cssm/

Subject: How to do GOTO in Matlab

From: ellieandrogerxyzzy@mindspring.com.invalid (Roger Stafford)

Date: 21 Dec, 2006 04:57:35

Message: 37 of 38

  As some of the articles in this thread attest, there seems to be a
prevalent point of view among many programmers that goes something like
this. a) Unrestricted gotos are clearly bad because they can lead to
spaghetti code that is difficult to decipher (which I agree with.)
Therefore, b) (which I disagree with) we programmers should be perfectly
content with the existing control structures of modern higher languages
that are limited to a minimal list, such as: if-else-end, while-end,
for-end, repeat-until (unfortunately not present in matlab), and
comparatively little else. There is frequently an effort to bolster this
argument with the statement that c) any algorithm can always be realized
with just the constructs on this list, so what is wrong with using only
those? - and often accompanied by a challenge of the sort, "any good
programmer worth his salt can do it."

  I claim this reasoning is specious. To begin with, being able to
realize a desired algorithm with a given, limited set of resources, even
though it may allow a programmer to exhibit great skill in doing so, does
not mean that this is the way things *should* be done. Even Turing
machines have been shown to have the capacity to implement any procedure
that could ever be carried out on any other possible computer, but no-one
seriously suggests that we actually use these machines for practical
computing. In practice, whatever devices we use in computing should have
the goal of producing results with the best combination of execution time
and cost, and that applies to programming techniques and languages as well
as the physical machines.

  As for the statement that the above restricted list is the only
reasonable alternative to the chaos of unrestricted gotos, I claim that is
specious reasoning too. Yes, unrestricted gotos are bad, but precisely
because they are unrestricted. A jump into one section of code from
another distant section of a program can produce very undesirable results
because it may not have been anticipated or remembered by the programmer
during the design of the first section. The key ingredient here in such
structures as if-else-end is that they have an understood limited "scope",
a range, extending from the "if" on down to the "end" which is usually
made evident by appropriate indentations in the written code, and the
compiler is designed so that nothing can jump into or out of this range
(well almost nothing) from or to distant points outside except for the
single entrance and exit. And this is as it should be. A programmer
designing an if-else-end piece of code needs to have just that kind of
assurance to avoid unforeseen circumstances arising within his code.

  But there is no reason other kinds of limited-scope structures than
those now used can't work equally well. What I would like to see is
programmers asking for, even clamoring for, a richer variety of such
structures by those who devise higher languages. I want to see the
structure I described earlier in this thread and others like it made
available without resort to illicit gotos. In short, I want to give
compiler writers a lot more work to do. It should all work properly as
long as such structures follow the same rules of scope for jumps as with
the present list. No jumps should be possible to other than to specified
entrances or from specified exits, but within the scope there should be
allowed a larger variety of possible jumps. Again I state my
"kindergartners'" criterion for an acceptable control structure. If a
diagram illustrating a control structure could be drawn on a blackboard
that kindergartners could readily understand, that is something that
probably should be made available in the language.

  The pressures against, or exclusions of, gotos have been in effect now
in our computing world for something like four decades, and there is a
tendency to look on them with an emotional distaste which I feel goes well
beyond what is warranted. The truth is that underlying the actions of all
compiled code are great quantities of conditional and unconditional jump
instructions. They are the very stuff of life for programs, and computing
would be impossible without them. Yet a jump is just what a goto does.
The idea should not be to avoid them; that would be impossible. Instead
they should be used in appropriate ways and under the appropriate
controls, but, in my opinion, in such a way as to provide a far wider
selection of control structures than is available now. And it should be
the higher languages and their compilers that are upgraded and revised so
as to make all this possible, rather than programmers having to insert
badly needed gotos here and there in their code while looking guiltily
over their shoulders.

Roger Stafford

Subject: How to do GOTO in Matlab

From: Jim Rockford

Date: 21 Dec, 2006 01:18:27

Message: 38 of 38

Bjorn Gustavsson wrote:
> Go To wrote:
> >
> >
> > The number of (negative) reactions raised every time the
> > GOTO issue resurfaces is a clear evidence of the bad
> > conscience of those who deny its utility.
> >
> But goto is so 1960s. Nowadays there are far more powerful constructs
> for creating program flow...
>
> ...what I would like to see in matlab is some of the funnier
> constructs from occam: par, channel arrays, process replicator...

I'd like to see Matlab re-introduce the response 'your place or mine?'
in response to a certain user command.

Jim

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
neperian logarithm Virginia 29 Jul, 2011 10:46:18
rssFeed for this Thread

Contact us at files@mathworks.com