Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Reasons for which functions are not allowed within scripts?

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 13 Dec, 2010 19:31:04

Message: 1 of 47

Hello everybody,

I am going to describe something that bugs me a lot in matlab:
"The inability of defining functions within scripts"

Why would I want to do that?

1) To write cleaner looking code
2) Because I don't want to create an .m file for a small function which usefulness is only within the script itself
3) Because if I wrap everything in a main() function rather than in a script, at the end of the call the context of the function gets wiped. I often that data context for data inspection thus having it wiped is annoying...
4) Code replication: sometimes I need to call the same function a bunch of times but I really don't want to have to C&P the code (clean in example below)

This is what I would like to be able to do:
----- main.m ----
clc, clear, close all;
[X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
Z = X .*sin(3*(+X.^2 - Y.^2));
figure, myplot(X,Y,Z);
Z = X .* exp(-X.^2 - Y.^2);
figure, myplot(X,Y,Z);

function myplot(X,Y,Z)
  f = gcf;
  p = surf(X,Y,Z);
  axis off;
  set(p,'edgecolor','none');
  camlight;
  set(p,'faceLighting','phong')
  set(f,'color','white');
  hold on;
  colormap('hot');
  [~,IMIN] = min(Z(:));
  [~,IMAX] = max(Z(:));
  plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
  plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
end
---- end of main.m ----

This is the alternative way of using a function, but when you execute it, the X,Y,Z variables will be cleared on function exit:

----- main.m ----
function main()
clc, clear, close all;
[X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
Z = X .*sin(3*(+X.^2 - Y.^2));
figure, myplot(X,Y,Z);
Z = X .* exp(-X.^2 - Y.^2);
figure, myplot(X,Y,Z);

function myplot(X,Y,Z)
  f = gcf;
  p = surf(X,Y,Z);
  axis off;
  set(p,'edgecolor','none');
  camlight;
  set(p,'faceLighting','phong')
  set(f,'color','white');
  hold on;
  colormap('hot');
  [~,IMIN] = min(Z(:));
  [~,IMAX] = max(Z(:));
  plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
  plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
end
end %--- end of function main
---- end of main.m ----
 
Any thought?
I think this would be something that it is about time to allow MATLAB users to do!

Subject: Reasons for which functions are not allowed within scripts?

From: Ryan Miller

Date: 13 Dec, 2010 20:20:09

Message: 2 of 47

If you want to hang on to the variables, why not just declare them as global? Keeping everything in functions seems nice for housekeeping purposes.

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 13 Dec, 2010 21:09:07

Message: 3 of 47

> If you want to hang on to the variables, why not just declare them as global? Keeping everything in functions seems nice for housekeeping purposes.

Well, that's pretty ugly. That's why.
You would have to mark every single one of them explicitly.

Also, the 2nd solution I proposed is not the optimal, IMHO a script should be considered as a function with an implicit parameterless call and without a change of scope. Thus, it should be a feasible thing to do (for matlab people) ...

Subject: Reasons for which functions are not allowed within scripts?

From: TideMan

Date: 13 Dec, 2010 21:16:33

Message: 4 of 47

On Dec 14, 8:31 am, "Andrea Tagliasacchi"
<andrea.tagliasac...@gmail.com> wrote:
> Hello everybody,
>
> I am going to describe something that bugs me a lot in matlab:
> "The inability of defining functions within scripts"
>
> Why would I want to do that?
>
> 1) To write cleaner looking code
> 2) Because I don't want to create an .m file for a small function which usefulness is only within the script itself
> 3) Because if I wrap everything in a main() function rather than in a script, at the end of the call the context of the function gets wiped. I often that data context for data inspection thus having it wiped is annoying...
> 4) Code replication: sometimes I need to call the same function a bunch of times but I really don't want to have to C&P the code (clean in example below)
>
> This is what I would like to be able to do:
> ----- main.m ----
> clc, clear, close all;
> [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> Z = X .*sin(3*(+X.^2 - Y.^2));
> figure, myplot(X,Y,Z);
> Z =  X .* exp(-X.^2 - Y.^2);
> figure, myplot(X,Y,Z);
>
> function myplot(X,Y,Z)
>   f = gcf;
>   p = surf(X,Y,Z);
>   axis off;
>   set(p,'edgecolor','none');
>   camlight;
>   set(p,'faceLighting','phong')
>   set(f,'color','white');
>   hold on;
>   colormap('hot');
>   [~,IMIN] = min(Z(:));
>   [~,IMAX] = max(Z(:));
>   plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
>   plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
> end
> ---- end of main.m ----
>
> This is the alternative way of using a function, but when you execute it, the X,Y,Z variables will be cleared on function exit:
>
> ----- main.m ----
> function main()
> clc, clear, close all;
> [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> Z = X .*sin(3*(+X.^2 - Y.^2));
> figure, myplot(X,Y,Z);
> Z =  X .* exp(-X.^2 - Y.^2);
> figure, myplot(X,Y,Z);
>
> function myplot(X,Y,Z)
>   f = gcf;
>   p = surf(X,Y,Z);
>   axis off;
>   set(p,'edgecolor','none');
>   camlight;
>   set(p,'faceLighting','phong')
>   set(f,'color','white');
>   hold on;
>   colormap('hot');
>   [~,IMIN] = min(Z(:));
>   [~,IMAX] = max(Z(:));
>   plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
>   plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
> end
> end %--- end of function main
> ---- end of main.m ----
>
> Any thought?
> I think this would be something that it is about time to allow MATLAB users to do!

Personally, I have no problem making a separate function that is
called from the script.
Usually, the most difficult thing is thinking of a unique name that is
meaningful.
Often, having created the function, one finds a use for it elsewhere
as well, particularly if one takes some care in writing to include
options using varargin.
For example, in your example, in the function myplot I'd make color,
colormap, and markersize variables so that the default is
myplot(X,Y,Z), but the variables can be changed like this:
myplot(X,Y,Z,...
    'color','red',...
    'colormap','pink',...
    'markersize',25)

Now, myplot is a function that could be used in lots of places.

Subject: Reasons for which functions are not allowed within scripts?

From: Dragan

Date: 13 Dec, 2010 21:25:29

Message: 5 of 47

Why not just return the variables from the function, even though the function only is plotting something?

I.e. function [a b c] = myplot(x,y,z)

and then just use it as [a b c] = myplot(x,y,z); in your main.m file. In this way you will also get a cleaner code IMO.

Subject: Reasons for which functions are not allowed within scripts?

From: Matt J

Date: 13 Dec, 2010 21:57:04

Message: 6 of 47

"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ie5s9o$jef$1@fred.mathworks.com>...
>
> 3) Because if I wrap everything in a main() function rather than in a script, at the end of the call the context of the function gets wiped. I often that data context for data inspection thus having it wiped is annoying...
=======

Why not stick in a keyboard command at the bottom of the main() function?Then you can work from the K>> prompt inside the workspace of main() just as you would work from the normal prompt.

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 13 Dec, 2010 22:18:05

Message: 7 of 47

Why not stick in a keyboard command at the bottom of the main() function?Then you can work from the >> prompt inside the workspace of main() just as you would work from the normal prompt.

What do you mean exactly? But this is still a hack no? You would still have sort of a breakpoint at the end of the function. That's what I used in a couple of occasions.

Subject: Reasons for which functions are not allowed within scripts?

From: Matt J

Date: 13 Dec, 2010 22:44:05

Message: 8 of 47

"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ie662t$qjt$1@fred.mathworks.com>...
> Why not stick in a keyboard command at the bottom of the main() function?Then you can work from the >> prompt inside the workspace of main() just as you would work from the normal prompt.
>
> What do you mean exactly?
=======

doc KEYBOARD

>But this is still a hack no? You would still have sort of a breakpoint at the end of the >function. That's what I used in a couple of occasions.
=================

How are breakpoints a hack? They were invented for doing precisely what you're describing (probing the results of a segment of a code). Moreover, they're very easy to add and later remove.

Generally speaking, scripts are dangerous things. Having variables leak unseen into the workspace of a script from the workspace that calls it means that you don't know from looking at the code what variables are in scope, and how they were initialized. That can make debugging very difficult. It's much better to isolate the workspace of the script from the surrounding code.

Subject: Reasons for which functions are not allowed within scripts?

From: Matt Fig

Date: 13 Dec, 2010 23:08:21

Message: 9 of 47

"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ie5s9o$jef$1@fred.mathworks.com>...
> Hello everybody,
>
> I am going to describe something that bugs me a lot in matlab:
> "The inability of defining functions within scripts"


I am glad for this feature! We already have subfunctions and nested functions. A script has its place, which thankfully cannot have "subfunctions." Imagine the debugging nightmares which could result from a function definition being permitted at the command line (as from a function-containing script called from there) or the nasty scoping issues which would result from a script subfunction called from within a function m-file containing nested functions. Yikes. No thanks.

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 15 Dec, 2010 16:46:07

Message: 10 of 47

You don't need to go that hardcore. Matlab could simply allow 1-level of functions (no nesting) in scripts only (no command line) and don't allow those functions to be scoped *outside* the script. It's not that hard and would allow for much more legible code!

> I am glad for this feature! We already have subfunctions and nested functions. A script has its place, which thankfully cannot have "subfunctions." Imagine the debugging nightmares which could result from a function definition being permitted at the command line (as from a function-containing script called from there) or the nasty scoping issues which would result from a script subfunction called from within a function m-file containing nested functions. Yikes. No thanks.

Subject: Reasons for which functions are not allowed within scripts?

From: Steven_Lord

Date: 15 Dec, 2010 18:50:17

Message: 11 of 47



"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
news:iearcf$818$1@fred.mathworks.com...
> You don't need to go that hardcore. Matlab could simply allow 1-level of
> functions (no nesting) in scripts only (no command line) and don't allow
> those functions to be scoped *outside* the script. It's not that hard and
> would allow for much more legible code!

It may be possible to do that; I haven't thought through all the
difficulties.

I have to question both parts of your assertion, though. It likely would be
hard to make sure there are no edge/special cases that will cause problems
other than the "something that's possible to do in scripts but not in the
command line", and "have a scope that's partway between script and function
file" special cases that you're already asking for. I also disagree that
the code would be any more legible than either converting your file into a
function file or pulling the subfunction into a separate file. [If you're
worried about namespacing, use a private function or a package directory.]

I also question whether there's sufficient demand for this feature -- I
don't remember the last time someone asked for this functionality.

But if you feel that strongly, submit this request (along with a clear
description of your use case) to Technical Support for capturing in the
enhancement database.

--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 16 Dec, 2010 18:15:24

Message: 12 of 47

MATLAB intro course (whereever you did it), lesson 2: "functions cannot be defined in scripts". That's why people don't bother... getting used to something is a powerful inhibitor.

How are the scripts managed internally? Very similarly to functions no?

Subject: Reasons for which functions are not allowed within scripts?

From: Walter Roberson

Date: 16 Dec, 2010 18:59:40

Message: 13 of 47

On 10-12-16 12:15 PM, Andrea Tagliasacchi wrote:
> MATLAB intro course (whereever you did it), lesson 2: "functions cannot be
> defined in scripts". That's why people don't bother... getting used to
> something is a powerful inhibitor.
>
> How are the scripts managed internally? Very similarly to functions no?

Scripts were handled fairly differently than functions up through Matlab
2010a, being more like exec() of the string content of the file.

In 2010b the internal processing of scripts become closer to functions.

Subject: Reasons for which functions are not allowed within scripts?

From: EBS

Date: 17 Dec, 2010 00:39:06

Message: 14 of 47

"Steven_Lord" <slord@mathworks.com> wrote in message <ieb2la$hnp$1@fred.mathworks.com>...
>
>
> "Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
> news:iearcf$818$1@fred.mathworks.com...
> > You don't need to go that hardcore. Matlab could simply allow 1-level of
> > functions (no nesting) in scripts only (no command line) and don't allow
> > those functions to be scoped *outside* the script. It's not that hard and
> > would allow for much more legible code!
>
> It may be possible to do that; I haven't thought through all the
> difficulties.
>
> I have to question both parts of your assertion, though. It likely would be
> hard to make sure there are no edge/special cases that will cause problems
> other than the "something that's possible to do in scripts but not in the
> command line", and "have a scope that's partway between script and function
> file" special cases that you're already asking for. I also disagree that
> the code would be any more legible than either converting your file into a
> function file or pulling the subfunction into a separate file. [If you're
> worried about namespacing, use a private function or a package directory.]
>
> I also question whether there's sufficient demand for this feature -- I
> don't remember the last time someone asked for this functionality.
>
> But if you feel that strongly, submit this request (along with a clear
> description of your use case) to Technical Support for capturing in the
> enhancement database.
>
> --
> Steve Lord
> slord@mathworks.com
> comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
> To contact Technical Support use the Contact Us link on
> http://www.mathworks.com

Steve, I for one have always thought this functionality would be nice to have, in the simple form outlined by Andrea. I think scripts are very popular among users, and I've seen some very ugly ones because there is no way to define local utility subfunctions. It would also make it easier to send your script to another user if you don't have to send a number of associated function files along for the ride.

I also seem to remember seeing a number of user requests for this functionality in the DB...

Regards,
EBS

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 17 Dec, 2010 09:27:05

Message: 15 of 47

> Steve, I for one have always thought this functionality would be nice to have, in the simple form outlined by Andrea. I think scripts are very popular among users, and I've seen some very ugly ones because there is no way to define local utility subfunctions. It would also make it easier to send your script to another user if you don't have to send a number of associated function files along for the ride.

Some very good points offered by Steve too.

How do you see whether there are open tickets? I went to the support site but I can only see the one that I opened myself in the past... Can I browse the bug-database? I don't want to submit duplicates...

Subject: Reasons for which functions are not allowed within scripts?

From: Steven_Lord

Date: 17 Dec, 2010 14:40:56

Message: 16 of 47



"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
news:iefad9$eng$1@fred.mathworks.com...
>> Steve, I for one have always thought this functionality would be nice to
>> have, in the simple form outlined by Andrea. I think scripts are very
>> popular among users, and I've seen some very ugly ones because there is
>> no way to define local utility subfunctions. It would also make it easier
>> to send your script to another user if you don't have to send a number of
>> associated function files along for the ride.

EBS's points are valid. However, if you're writing a piece of code
complicated or long enough to warrant having a number of utility
subfunctions, I would recommend converting that script file into a function
file to prevent possible workspace interference. This would allow you to
make your utility subfunctions into real subfunctions. Note that this
interference could go both ways -- your program putting variables in the
base workspace could cause another script that you run to give an unexpected
error or the wrong answer, or another script could do the same to your
program.

> Some very good points offered by Steve too.
> How do you see whether there are open tickets? I went to the support site
> but I can only see the one that I opened myself in the past... Can I
> browse the bug-database? I don't want to submit duplicates...

While we do make available information on some subset of reported bugs, we
don't offer full access to the internal bug and enhancement database. Don't
worry about submitting duplicate enhancement requests -- that allows us to
track how many users have requested a particular enhancement.

--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Reasons for which functions are not allowed within scripts?

From: EBS

Date: 17 Dec, 2010 19:29:05

Message: 17 of 47

"Steven_Lord" <slord@mathworks.com> wrote in message <iefspo$16k$1@fred.mathworks.com>...
>
>
> "Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
> news:iefad9$eng$1@fred.mathworks.com...
> >> Steve, I for one have always thought this functionality would be nice to
> >> have, in the simple form outlined by Andrea. I think scripts are very
> >> popular among users, and I've seen some very ugly ones because there is
> >> no way to define local utility subfunctions. It would also make it easier
> >> to send your script to another user if you don't have to send a number of
> >> associated function files along for the ride.
>
> EBS's points are valid. However, if you're writing a piece of code
> complicated or long enough to warrant having a number of utility
> subfunctions, I would recommend converting that script file into a function
> file to prevent possible workspace interference. This would allow you to
> make your utility subfunctions into real subfunctions. Note that this
> interference could go both ways -- your program putting variables in the
> base workspace could cause another script that you run to give an unexpected
> error or the wrong answer, or another script could do the same to your
> program.
>
(snip)
> Steve Lord
> slord@mathworks.com
> comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
> To contact Technical Support use the Contact Us link on
> http://www.mathworks.com

Steve, along these lines I've thought it would be cool to be able to programatically/GUI create new workspaces other than the base one. I think this would go a long way to alleviate your concerns about scripts polluting the base WS, which tends to lead to the problematic "nuke it from orbit" approach of 'clear all' at the top of many people's scripts...

I'm thinking the end effect would be similar to converting the script to a function with no inputs or outputs and then putting a 'keyboard' command at the end - after it runs you could examine all the variables in the new named workspace, see what's in the base (& other) workspaces, etc without polluting the base WS.

Has this ever been discussed or submitted as a enhancement request?

Best,
Eric

Subject: Reasons for which functions are not allowed within scripts?

From: Bjorn Gustavsson

Date: 17 Dec, 2010 20:11:21

Message: 18 of 47

"EBS " <ericDOTsampson@gmail.com> wrote in message <iegdm1$nmm$1@fred.mathworks.com>...
>
[snip]
>
> Steve, along these lines I've thought it would be cool to be able to
> programatically/GUI create new workspaces other than the base one. I think this
> would go a long way to alleviate your concerns about scripts polluting the base
> WS, which tends to lead to the problematic "nuke it from orbit" approach of
> 'clear all' at the top of many people's scripts...
>
> I'm thinking the end effect would be similar to converting the script to a function
> with no inputs or outputs and then putting a 'keyboard' command at the end -
> after it runs you could examine all the variables in the new named workspace, see
> what's in the base (& other) workspaces, etc without polluting the base WS.
>
I once wrote a very minimalistic function that you could call without (or with a list of variables) that essentially only contains a keyboard statement - allowing usage of clean workspaces:
http://www.mathworks.com/matlabcentral/fileexchange/2491-wsptmp


There is also another such tool - much more advanced with all sorts of impressive bells and whistles - that was once a fex-pick-o-the-week.

Regards,
Bjeorn

Subject: Reasons for which functions are not allowed within scripts?

From: Steven_Lord

Date: 17 Dec, 2010 21:59:49

Message: 19 of 47



"EBS " <ericDOTsampson@gmail.com> wrote in message
news:iegdm1$nmm$1@fred.mathworks.com...
> "Steven_Lord" <slord@mathworks.com> wrote in message
> <iefspo$16k$1@fred.mathworks.com>...
>>
>>
>> "Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
>> news:iefad9$eng$1@fred.mathworks.com...
>> >> Steve, I for one have always thought this functionality would be nice
>> >> to have, in the simple form outlined by Andrea. I think scripts are
>> >> very popular among users, and I've seen some very ugly ones because
>> >> there is no way to define local utility subfunctions. It would also
>> >> make it easier to send your script to another user if you don't have
>> >> to send a number of associated function files along for the ride.
>>
>> EBS's points are valid. However, if you're writing a piece of code
>> complicated or long enough to warrant having a number of utility
>> subfunctions, I would recommend converting that script file into a
>> function file to prevent possible workspace interference. This would
>> allow you to make your utility subfunctions into real subfunctions. Note
>> that this interference could go both ways -- your program putting
>> variables in the base workspace could cause another script that you run
>> to give an unexpected error or the wrong answer, or another script could
>> do the same to your program.
>>
> (snip)
>> Steve Lord
>> slord@mathworks.com
>> comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
>> To contact Technical Support use the Contact Us link on
>> http://www.mathworks.com
>
> Steve, along these lines I've thought it would be cool to be able to
> programatically/GUI create new workspaces other than the base one. I think
> this would go a long way to alleviate your concerns about scripts
> polluting the base WS, which tends to lead to the problematic "nuke it
> from orbit" approach of 'clear all' at the top of many people's scripts...
>
> I'm thinking the end effect would be similar to converting the script to a
> function with no inputs or outputs and then putting a 'keyboard' command
> at the end - after it runs you could examine all the variables in the new
> named workspace, see what's in the base (& other) workspaces, etc without
> polluting the base WS.
>
> Has this ever been discussed or submitted as a enhancement request?

I honestly don't know, but it wouldn't hurt to submit it and explain how you
would use such a functionality.

--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Reasons for which functions are not allowed within scripts?

From: Alan B

Date: 17 Dec, 2010 22:08:04

Message: 20 of 47

"EBS " <ericDOTsampson@gmail.com> wrote in message <ieebfa$9os$1@fred.mathworks.com>...
> "Steven_Lord" <slord@mathworks.com> wrote in message <ieb2la$hnp$1@fred.mathworks.com>...
> >
> >
> > "Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
> > news:iearcf$818$1@fred.mathworks.com...
> > > You don't need to go that hardcore. Matlab could simply allow 1-level of
> > > functions (no nesting) in scripts only (no command line) and don't allow
> > > those functions to be scoped *outside* the script. It's not that hard and
> > > would allow for much more legible code!
> >
> > It may be possible to do that; I haven't thought through all the
> > difficulties.
> >
> > I have to question both parts of your assertion, though. It likely would be
> > hard to make sure there are no edge/special cases that will cause problems
> > other than the "something that's possible to do in scripts but not in the
> > command line", and "have a scope that's partway between script and function
> > file" special cases that you're already asking for. I also disagree that
> > the code would be any more legible than either converting your file into a
> > function file or pulling the subfunction into a separate file. [If you're
> > worried about namespacing, use a private function or a package directory.]
> >
> > I also question whether there's sufficient demand for this feature -- I
> > don't remember the last time someone asked for this functionality.
> >
> > But if you feel that strongly, submit this request (along with a clear
> > description of your use case) to Technical Support for capturing in the
> > enhancement database.
> >
> > --
> > Steve Lord
> > slord@mathworks.com
> > comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
> > To contact Technical Support use the Contact Us link on
> > http://www.mathworks.com
>
> Steve, I for one have always thought this functionality would be nice to have, in the simple form outlined by Andrea. I think scripts are very popular among users, and I've seen some very ugly ones because there is no way to define local utility subfunctions. It would also make it easier to send your script to another user if you don't have to send a number of associated function files along for the ride.
>
> I also seem to remember seeing a number of user requests for this functionality in the DB...
>
> Regards,
> EBS

I would use this functionality as well, I find myself in Andrea's situation regularly. I usually choose to change the script into a function, and add a keyboard statement at the bottom, but that has always felt like a hack to me. It never occurred to me to ask to be able to define functions within scripts, because I assumed there was some architectural issue making it all but impossible.

Subject: Reasons for which functions are not allowed within scripts?

From: Bob S

Date: 3 Jan, 2011 23:57:07

Message: 21 of 47

I couldn't agree more. It bugs me a lot too. (I would also add inability to define functions on the command line, although that's much less important.)

I'd like to know if there's any good reason why these restrictions exist, apart from historical reasons. They seem extremely arbitrary and I imagine they're probably easy to remove.

In Andrea's case, I presume it would be a reasonable (although undesirable) restriction if the functions are required to be defined before they're referred to in the script.

I note this is issue also referenced in thread 241943.


"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ie5s9o$jef$1@fred.mathworks.com>...
> Hello everybody,
>
> I am going to describe something that bugs me a lot in matlab:
> "The inability of defining functions within scripts"
>
> Why would I want to do that?
>
> 1) To write cleaner looking code
> 2) Because I don't want to create an .m file for a small function which usefulness is only within the script itself
> 3) Because if I wrap everything in a main() function rather than in a script, at the end of the call the context of the function gets wiped. I often that data context for data inspection thus having it wiped is annoying...
> 4) Code replication: sometimes I need to call the same function a bunch of times but I really don't want to have to C&P the code (clean in example below)
>
> This is what I would like to be able to do:
> ----- main.m ----
> clc, clear, close all;
> [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> Z = X .*sin(3*(+X.^2 - Y.^2));
> figure, myplot(X,Y,Z);
> Z = X .* exp(-X.^2 - Y.^2);
> figure, myplot(X,Y,Z);
>
> function myplot(X,Y,Z)
> f = gcf;
> p = surf(X,Y,Z);
> axis off;
> set(p,'edgecolor','none');
> camlight;
> set(p,'faceLighting','phong')
> set(f,'color','white');
> hold on;
> colormap('hot');
> [~,IMIN] = min(Z(:));
> [~,IMAX] = max(Z(:));
> plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
> plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
> end
> ---- end of main.m ----
>
> This is the alternative way of using a function, but when you execute it, the X,Y,Z variables will be cleared on function exit:
>
> ----- main.m ----
> function main()
> clc, clear, close all;
> [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> Z = X .*sin(3*(+X.^2 - Y.^2));
> figure, myplot(X,Y,Z);
> Z = X .* exp(-X.^2 - Y.^2);
> figure, myplot(X,Y,Z);
>
> function myplot(X,Y,Z)
> f = gcf;
> p = surf(X,Y,Z);
> axis off;
> set(p,'edgecolor','none');
> camlight;
> set(p,'faceLighting','phong')
> set(f,'color','white');
> hold on;
> colormap('hot');
> [~,IMIN] = min(Z(:));
> [~,IMAX] = max(Z(:));
> plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
> plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
> end
> end %--- end of function main
> ---- end of main.m ----
>
> Any thought?
> I think this would be something that it is about time to allow MATLAB users to do!

Subject: Reasons for which functions are not allowed within scripts?

From: Greg Heath

Date: 4 Jan, 2011 05:46:30

Message: 22 of 47

On Jan 3, 6:57 pm, "Bob S" <rvsass...@hotmail.dropthis.com> wrote:
> I couldn't agree more. It bugs me a lot too. (I would also add inability to define functions on the command line, although that's much less important.)
>
> I'd like to know if there's any good reason why these restrictions exist, apart from historical reasons. They seem extremely arbitrary and I imagine they're probably easy to remove.
>
> In Andrea's case, I presume it would be a reasonable (although undesirable) restriction if the functions are required to be defined before they're referred to in the script.
>
> I note this is issue also referenced in thread 241943.

How do I access "thread 241943"?

Greg

Subject: Reasons for which functions are not allowed within scripts?

From: Husam Aldahiyat

Date: 4 Jan, 2011 07:41:04

Message: 23 of 47

Greg Heath <heath@alumni.brown.edu> wrote in message <20a9b2c5-5fed-4a49-a680-26d6faf28c16@n10g2000yqd.googlegroups.com>...
> On Jan 3, 6:57 pm, "Bob S" <rvsass...@hotmail.dropthis.com> wrote:
> > I couldn't agree more. It bugs me a lot too. (I would also add inability to define functions on the command line, although that's much less important.)
> >
> > I'd like to know if there's any good reason why these restrictions exist, apart from historical reasons. They seem extremely arbitrary and I imagine they're probably easy to remove.
> >
> > In Andrea's case, I presume it would be a reasonable (although undesirable) restriction if the functions are required to be defined before they're referred to in the script.
> >
> > I note this is issue also referenced in thread 241943.
>
> How do I access "thread 241943"?
>
> Greg

http://www.mathworks.com/matlabcentral/newsreader/view_thread/241943

Subject: Reasons for which functions are not allowed within scripts?

From: Greg Heath

Date: 4 Jan, 2011 08:31:43

Message: 24 of 47

On Dec 13 2010, 2:31 pm, "Andrea Tagliasacchi"
<andrea.tagliasac...@gmail.com> wrote:
> Hello everybody,
>
> I am going to describe something that bugs me a lot in matlab:
> "The inability of defining functions within scripts"
-----SNIP
> Any thought?
> I think this would be something that it is about time
> to allow MATLAB users to do!

My workaround is stored in file myplotexample.m
with contents

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [X, Y, Z1, Z2] = myplotexample;
[X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
Z1 = X .*sin(3*(+X.^2 - Y.^2));
Z2 = X .* exp(-X.^2 - Y.^2);
figure, myplot(X,Y,Z1);
figure, myplot(X,Y,Z2);

function myplot(X,Y,Z)
  f = gcf;
  p = surf(X,Y,Z);
  axis off;
  set(p,'edgecolor','none');
  camlight;
  set(p,'faceLighting','phong')
  set(f,'color','white');
  hold on;
  colormap('hot');
  [Zmin,IMIN] = min(Z(:));
  [Zmax,IMAX] = max(Z(:));
  plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
  plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);

return

 close all; clear all; clc;
 [X, Y, Z1, Z2] = myplotexample;
 whos

% whos
% U = ans;
% [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
% isX = isequal(U,X)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

1. When I cut and paste the three lines below "return",
   into the command line everything is OK
2. When I open the file and click on debug/run

   a. The plots are OK
   b. I do not see the result of whos
   c. Something is printed to the screen.
   d. When I type "whos" into the command line I see
      only 1 variable named ans with the same size as
      X,Y, Z1 and Z2.
   e. Setting U = ans and recreating X,I find that
      U = X (See the commented code at the end).

  However, I do not know where U is coming from.

3. I get the same results when I type "myplotexample"
    into the command line

Comments?

Greg

Subject: Reasons for which functions are not allowed within scripts?

From: Malcolm McLean

Date: 4 Jan, 2011 08:33:04

Message: 25 of 47

"Ryan Miller" wrote in message <ie5v5p$ejn$1@fred.mathworks.com>...
> If you want to hang on to the variables, why not just declare them as global?
> Keeping everything in functions seems nice for housekeeping purposes.

I often get this problem: I want to run a fairly long calculation on an external dataset. Since I'm hardcoding the path to the data, a script is appropriate. I'll also print out the analysis.
However it's very easy to introduce a trivial bug which messes up the printing. So you want the data to still be there. Then you can correct the print, and just run the output portion of the script again.

Subject: Reasons for which functions are not allowed within scripts?

From: Gary

Date: 5 Jan, 2011 14:52:05

Message: 26 of 47

I also would like to see that feature. I find that I often put breakpoints at the end of my functions so that I can have access to the data for investigation, visualization, etc.

Gary

Subject: Reasons for which functions are not allowed within scripts?

From: Walter Roberson

Date: 5 Jan, 2011 15:02:24

Message: 27 of 47

On 05/01/11 8:52 AM, Gary wrote:
> I also would like to see that feature. I find that I often put
> breakpoints at the end of my functions so that I can have access to the
> data for investigation, visualization, etc.

I don't understand, Gary, how allowing functions to be defined within
scripts would assist you with that matter? Functions that were
hypothetically defined within scripts would still retain the same
behavior of having their variable values disappear when the function
itself terminated.

Subject: Reasons for which functions are not allowed within scripts?

From: Gary

Date: 5 Jan, 2011 15:22:05

Message: 28 of 47

> I don't understand, Gary, how allowing functions to be defined within
> scripts would assist you with that matter? Functions that were
> hypothetically defined within scripts would still retain the same
> behavior of having their variable values disappear when the function
> itself terminated.

Sorry for my lack of clarity. The breakpoints go in the top-level function (the one that I would rather make into a script), not the subfunctions.

Subject: Reasons for which functions are not allowed within scripts?

From: Matt Fig

Date: 5 Jan, 2011 15:23:04

Message: 29 of 47

Walter Roberson <roberson@hushmail.com> wrote in message <5K%Uo.1840$rG3.1555@newsfe09.iad>...
> On 05/01/11 8:52 AM, Gary wrote:
> > I also would like to see that feature. I find that I often put
> > breakpoints at the end of my functions so that I can have access to the
> > data for investigation, visualization, etc.
>
> I don't understand, Gary, how allowing functions to be defined within
> scripts would assist you with that matter? Functions that were
> hypothetically defined within scripts would still retain the same
> behavior of having their variable values disappear when the function
> itself terminated.

Not to mention other weirdities, such as: what if a script containing a function was called within a FOR loop? Are we now going to allow function definitions within FOR loops? What is the scope of the function's variables, and is the iterating variable available to the function, or does it need to be passed in? Or other variables outside the FOR loop but within the main function? Let's not even think about adding nested functions to the list of possibilities!

Subject: Reasons for which functions are not allowed within scripts?

From: Oleg Komarov

Date: 5 Jan, 2011 15:31:05

Message: 30 of 47

"Gary" wrote in message <ig22at$bd8$1@fred.mathworks.com>...
> > I don't understand, Gary, how allowing functions to be defined within
> > scripts would assist you with that matter? Functions that were
> > hypothetically defined within scripts would still retain the same
> > behavior of having their variable values disappear when the function
> > itself terminated.
>
> Sorry for my lack of clarity. The breakpoints go in the top-level function (the one that I would rather make into a script), not the subfunctions.

Your answer makes no sense. You set breakpoints at any level and once set you can travel down or up.

Oleg

Subject: Reasons for which functions are not allowed within scripts?

From: Walter Roberson

Date: 5 Jan, 2011 15:37:31

Message: 31 of 47

On 05/01/11 9:22 AM, Gary wrote:
>> I don't understand, Gary, how allowing functions to be defined within
>> scripts would assist you with that matter? Functions that were
>> hypothetically defined within scripts would still retain the same
>> behavior of having their variable values disappear when the function
>> itself terminated.
>
> Sorry for my lack of clarity. The breakpoints go in the top-level
> function (the one that I would rather make into a script), not the
> subfunctions.

Are you using shared variables (nested functions)? If not, then why not
just write the sub-functions into other files and make your current
top-level function in to a script? If you are concerned about
proliferation of files, use the "package" structure, or use the
"switchboard" construct (that is, put all of the secondary functions in
to a single file topped with a function that returns handles to all of
them that need to be called directly from the upper level).

Subject: Reasons for which functions are not allowed within scripts?

From: Gary

Date: 5 Jan, 2011 16:00:26

Message: 32 of 47


><snip> If you are concerned about proliferation of files<snip>

That is exactly it. Let's say I want to visualize the contents of a large data file. I'll read the file, parse the data as necessary, do some simple manipulation, then perform some plotting. Just as the original poster indicated, the plotting might have enough properties set that it makes sense to create a function (vs. copying and pasting a handful of lines).

Because I'm investigating the data, I might find that I want to parse differently, then look at it again. In order to save myself the time associated with rereading the datafile every time I want to look at the data, I figure I have 3 options if I want to be able to use a plotting function as described at the top of the previous paragraph (and yes, I'm sure there are others I haven't listed here)

1) Create a top-level function with output structures or a list of variables and define the plotting function as a subfunction.
2) Create and save the plotting function separately as its own m file.
3) Create a top-level function and define the plotting function as a subfunction, then put a breakpoint at the end of the top-level function to keep it from completing and therefore wiping my workspace. A variant is to use the keyboard approach that someone else suggested.

Option 1 certainly works well. There's nothing technically wrong with it, but isn't the whole purpose of supporting scripts so that we don't have to do this?

Option 2 also works, but if I don't expect to use the plotting function again, then file management becomes a nuisance.

Option 3 is a hack, which could be prevented by introducing the ability to have subfunctions inside scripts, as the original poster requested.

Subject: Reasons for which functions are not allowed within scripts?

From: Steven_Lord

Date: 5 Jan, 2011 18:00:32

Message: 33 of 47



"Gary" <grubin698@gmail.com> wrote in message
news:ig24iq$6sc$1@fred.mathworks.com...
>
>><snip> If you are concerned about proliferation of files<snip>
>
> That is exactly it. Let's say I want to visualize the contents of a large
> data file. I'll read the file, parse the data as necessary, do some
> simple manipulation, then perform some plotting. Just as the original
> poster indicated, the plotting might have enough properties set that it
> makes sense to create a function (vs. copying and pasting a handful of
> lines).
>
> Because I'm investigating the data, I might find that I want to parse
> differently, then look at it again. In order to save myself the time
> associated with rereading the datafile every time I want to look at the
> data, I figure I have 3 options if I want to be able to use a plotting
> function as described at the top of the previous paragraph (and yes, I'm
> sure there are others I haven't listed here)

So if you're "investigating the data" I assume you loaded it into the base
workspace in the Command Window so you can experiment -- if that's the case,
it makes sense for your plotting routine to be a function into which you
pass the data as an input argument. Or it makes sense for you to have the
Command History window open so that you can select a block of commands and
execute them all at once rather than copying and pasting each individual
line.

http://www.mathworks.com/help/techdoc/matlab_env/f0-17420.html

> 1) Create a top-level function with output structures or a list of
> variables and define the plotting function as a subfunction.
> 2) Create and save the plotting function separately as its own m file.
> 3) Create a top-level function and define the plotting function as a
> subfunction, then put a breakpoint at the end of the top-level function to
> keep it from completing and therefore wiping my workspace. A variant is
> to use the keyboard approach that someone else suggested.
>
> Option 1 certainly works well. There's nothing technically wrong with it,
> but isn't the whole purpose of supporting scripts so that we don't have to
> do this?
>
> Option 2 also works, but if I don't expect to use the plotting function
> again, then file management becomes a nuisance.

If you're worried about the plotting function consuming namespace, then make
it a private function or a package function depending on what other
functions need to make use of it.

If only functions in this directory need to use it, put it in a subdirectory
of the current directory that is named "private".

http://www.mathworks.com/help/techdoc/matlab_prog/f4-70335.html

If functions outside this directory need to use it, put it in a package
directory and invoke it using the package syntax.

http://www.mathworks.com/help/techdoc/matlab_oop/brfynt_-1.html

While this is part of the object-oriented programming documentation, it is
not limited to only containing objects.

> Option 3 is a hack, which could be prevented by introducing the ability to
> have subfunctions inside scripts, as the original poster requested.

Would there be some benefit to allowing subfunctions inside scripts? You
and other posters have indicated that you think there would be.
Would there be additional complexity involved in allowing this? Absolutely.
Does the former outweigh the latter? Personally, I do not believe it does.

--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlab.wikia.com/wiki/FAQ
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Reasons for which functions are not allowed within scripts?

From: dpb

Date: 5 Jan, 2011 18:55:12

Message: 34 of 47

Gary wrote:
>
>> <snip> If you are concerned about proliferation of files<snip>
>
> That is exactly it. Let's say I want to visualize the contents of a
> large data file. ...
>
> Because I'm investigating the data, I might find that I want to parse
> differently, then look at it again. In order to save myself the time
> associated with rereading the datafile every time I want to look at the
> data, ...

I fail to see why one then can't simply keep the data in the base
workspace and call whatever functions w/ it one desires.

What's the physical difference in writing a function vis a vis writing a
script?

--

Subject: Reasons for which functions are not allowed within scripts?

From: Daniel

Date: 5 Jan, 2011 19:37:04

Message: 35 of 47

While I am one of the people against functions in scripts, if that is really what you want ...

What about reading all the variables in the base workspace into the function workspace at the beginning and then writing the variables in the function workspace into the base workspace at the end? Something like:

names = evalin('base', 'who');
for iname = 1:length(names)
temp = evalin('base', names{iname});
eval([names{iname}, ' = temp;']);
end
clear names iname temp

and

names = who;
for iname = 1:length(names)
assignin('base', names{iname}, eval(names{iname}))
end

If Matlab's copy on write can handle eval, evalin, and assignin, then it should be fairly quick and not take any extra memory.

Subject: Reasons for which functions are not allowed within scripts?

From: Tod

Date: 5 Jan, 2011 20:29:05

Message: 36 of 47

"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ie5s9o$jef$1@fred.mathworks.com>...
> Hello everybody,

> This is what I would like to be able to do:
> ----- main.m ----
> clc, clear, close all;
> [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> Z = X .*sin(3*(+X.^2 - Y.^2));
> figure, myplot(X,Y,Z);
> Z = X .* exp(-X.^2 - Y.^2);
> figure, myplot(X,Y,Z);
>
> function myplot(X,Y,Z)
> f = gcf;
...
> end
> ---- end of main.m ----
>

>

I'm pretty new to MatLab so I may not fully understand the subtleties of your question but it seems like the bulk of what you want to do can be accomplished by creating a classdef. You create properties for the values you want to be persistent (like X,Y and Z). Then from the command line you can do something like

mp = MyPlot;
mp.Z = mp.X .*sin(3*(+mp.X.^2 - mp.Y.^2));
mp.myPlot()

Subject: Reasons for which functions are not allowed within scripts?

From: Sean de

Date: 20 Jan, 2011 15:32:04

Message: 37 of 47

"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ie5s9o$jef$1@fred.mathworks.com>...
> Hello everybody,
>
> I am going to describe something that bugs me a lot in matlab:
> "The inability of defining functions within scripts"
>
> Why would I want to do that?
>
> 1) To write cleaner looking code
> 2) Because I don't want to create an .m file for a small function which usefulness is only within the script itself
> 3) Because if I wrap everything in a main() function rather than in a script, at the end of the call the context of the function gets wiped. I often that data context for data inspection thus having it wiped is annoying...
> 4) Code replication: sometimes I need to call the same function a bunch of times but I really don't want to have to C&P the code (clean in example below)
>
> Any thought?
> I think this would be something that it is about time to allow MATLAB users to do!

To revive a deceased thread, here:
As the semester kicks off and I'm doing homework/lab reports in scripts I remember how useful this "function"ality could be. Using cell mode, MATLAB is able to create some really pretty automatically published documents. It's doable to define an external function for just the script and then call it within the script; however, this doesn't allow someone viewing the published report to see the contents of the function. If the function could be its own cell it would look pretty and be easily read.

Of course the function could be published separately and turned into HTML/LaTeX etc. then the script/function could be combined in that format. That seems sloppy though. Hmmm I may have just come up with the day's project.

Subject: Reasons for which functions are not allowed within scripts?

From: Steven_Lord

Date: 20 Jan, 2011 15:55:58

Message: 38 of 47



"Sean de " <sean.dewolski@nospamplease.umit.maine.edu> wrote in message
news:ih9khk$aep$1@fred.mathworks.com...
> "Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message
> <ie5s9o$jef$1@fred.mathworks.com>...
>> Hello everybody, I am going to describe something that bugs me a lot in
>> matlab:
>> "The inability of defining functions within scripts"
>>
>> Why would I want to do that? 1) To write cleaner looking code
>> 2) Because I don't want to create an .m file for a small function which
>> usefulness is only within the script itself
>> 3) Because if I wrap everything in a main() function rather than in a
>> script, at the end of the call the context of the function gets wiped. I
>> often that data context for data inspection thus having it wiped is
>> annoying...
>> 4) Code replication: sometimes I need to call the same function a bunch
>> of times but I really don't want to have to C&P the code (clean in
>> example below)
>>
>> Any thought? I think this would be something that it is about time to
>> allow MATLAB users to do!
>
> To revive a deceased thread, here:
> As the semester kicks off and I'm doing homework/lab reports in scripts I
> remember how useful this "function"ality could be. Using cell mode,
> MATLAB is able to create some really pretty automatically published
> documents. It's doable to define an external function for just the script
> and then call it within the script; however, this doesn't allow someone
> viewing the published report to see the contents of the function. If the
> function could be its own cell it would look pretty and be easily read.
>
> Of course the function could be published separately and turned into
> HTML/LaTeX etc. then the script/function could be combined in that format.
> That seems sloppy though. Hmmm I may have just come up with the day's
> project.

The ability to publish function files (which have the capability to include
subfunctions) was introduced in release R2008a:

http://www.mathworks.com/help/techdoc/rn/brga7wp-1.html#brg9eej-1

Use a publish configuration to do so.

http://www.mathworks.com/help/techdoc/matlab_env/briymz8-1.html

--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) user-generated FAQ:
http://matlab.wikia.com/wiki/FAQ
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Reasons for which functions are not allowed within scripts?

From: Øyvind

Date: 26 Jan, 2011 15:26:03

Message: 39 of 47

This is a piece of functionality that I really miss in Matlab, and which is available in other languages, such as Python, Ruby and Lua. I've always been wowed at the ability to create functions and classes and so on from Python's command line (and nested classes, which are as yet not possible in Matlab).

When I'm writing scripts I don't normally make a file or anything, it's just a sketch, 'Untitled3' or something in my editor. Often I will also just mark a few lines and run them using F9. It would be a major convenience to be able to have functions defined on the fly in my script or on the command line, instead of coming up with a place to store a temporary function m-file, coming up with a non-conflicting descriptive name, and also being unable to see the function definition itself within my script as I'm coding.

It is possibly a question of temperament or style, but I just dislike generating extra files that I know for sure will never be used again, and I'll sometimes go to ridiculous lengths to avoid it, as in trying to figure out exotic anonymous function definitions that will do what I want.

What I'd like to see is the possibility of doing

>> function [a,b] = mytempfunc(x,y), a = dosomething(x); b = dosomethingelse(y); end

from the commandline and, by extension, in scripts. mytempfunc would then show up as a function_handle in my workspace. Think of it as defining shorthand notation for more complicated operations. Which is of course what a function is, but, without having to create new files all the time, losing sight of what you are doing and fragmenting your code.

Oh, and nested class definitions. That would clean up my current project considerably.

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 26 Jan, 2011 16:39:04

Message: 40 of 47

Hello Everybody,

I suggest all the people that like this functionality to submit a feature request!
I have already done so few weeks ago. Let's hope to see them sometimes soon :)

Subject: Reasons for which functions are not allowed within scripts?

From: Charles

Date: 27 Jan, 2011 01:51:05

Message: 41 of 47

I've been working with Matlab for 14 years, and this restriction has been there the entire time. Yes, it is a pain sometimes, but I think it forces me to write better code.

One previous post mentioned calling a script in a loop causing problems... well, I've done that, and it's not pretty, but it got the job done. Another time, I had a big script that I changed to a function so I could call it more reliably in a loop - made a lot more sense to pass in parameters directly, rather than changing workspace variables.

As far as debugging, I have gotten quite used to putting breakpoints here and there to make sure I get to see some result before the function returns. Sometimes I feel I'm living in the debugger. But Matlab 2010b makes this much more enjoyable with the recent debugger-editor integration enhancements.

"Better code?" you might say. This was discussed early on in the thread. If you think you need a function, why not just write a new one in a separate file? That does tend to get tedious, too.

Or, you could write your script as a function and stuff all the results into a struct and return the struct. Everything in one place.

On the other hand, I find that stuff I've done in Matlab I keep coming back to because people ask me for the same thing again, with some slight difference. So, my Matlab code is written so I can reproduce results. I find that if I haven't done that, I usually regret it. So, I write my code using good SW programming practices. My Matlab is not just a series of calculations - it's structured like a C or C++ program.

I realize where Matlab came from and that certain things are legacies of that past. But I would push development more in the direction of Python, in which class hierarchies are defined by the directory (folder) structure itself. It's too difficult in Matlab to add things to the path in an organized way.

Well anyway, I'm sure someone has found workarounds to my own complaints about Matlab. But to me, I find the script limitation a bother sometimes, but an acceptable bother. I'd rather live with it than have some new perverse model of software structure that allowed functions in scripts.

Happy programming,

Charles Wright

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 27 Jan, 2011 02:34:04

Message: 42 of 47

> Well anyway, I'm sure someone has found workarounds to my own complaints about Matlab. But to me, I find the script limitation a bother sometimes, but an acceptable bother. I'd rather live with it than have some new perverse model of software structure that allowed functions in scripts.
> Charles Wright

Another user made a very good observation.. they are already allowed in scripts...
Anonymous functions can be declared within scripts. Their behavior should be similar, defining a function within a scripts simply creates a handle.

Yes, in the long term, functions are better. But you always start from small and grow.
Matlab is an excellent prototyping platform and this limitation make it less suitable for that purpose as you are forced to create files for functions...

Subject: Reasons for which functions are not allowed within scripts?

From: Øyvind

Date: 27 Jan, 2011 15:04:03

Message: 43 of 47

"Andrea Tagliasacchi" <andrea.tagliasacchi@gmail.com> wrote in message <ihqlir$hll$1@fred.mathworks.com>...
> Another user made a very good observation.. they are already allowed in scripts...
> Anonymous functions can be declared within scripts. Their behavior should be similar, defining a function within a scripts simply creates a handle.

I agree. And most of the objections against your suggestion are as far as I can tell objections against scripts in general, not objections against functions inside scripts per se.

One thing that has occurred to me, in response to some remarks higher up in the thread, is that although you can export your function workspace into the base workspace, it is harder to get the variables back _into_ a function, in the case that you want to continue running from where you left off, with every variable in the same (or tweaked) state. In a script you can ctrl-C, modify the script (convergence criteria, tweak parameters, whatever), and then restart the script at the point you left off. ctrl-C will kill a function, and you'll have to start over.

Subject: Reasons for which functions are not allowed within scripts?

From: Andrea Tagliasacchi

Date: 27 Jan, 2011 17:23:03

Message: 44 of 47

> I agree. And most of the objections against your suggestion are as far as I can tell objections against scripts in general, not objections against functions inside scripts per se.

Exactly... and script nesting is actually something I never needed/wanted to use.. When a script is too big, that's when I usually use save/load to temp files or I resort to functions.

Script nesting is bad... I cannot imagine why function in scripts will be ANY worse than scripts within scripts. The behavior should be exactly the same as the one of anonymous functions.

Let me underline again.. if you want this feature, let's all submit a feature request.
It can be very short, no need for a lengthy description...

Subject: Reasons for which functions are not allowed within scripts?

From: Think blue, count two.

Date: 27 Jan, 2011 17:54:44

Message: 45 of 47

On 26/01/11 8:34 PM, Andrea Tagliasacchi wrote:

> Another user made a very good observation.. they are already allowed in
> scripts...
> Anonymous functions can be declared within scripts. Their behavior
> should be similar, defining a function within a scripts simply creates a
> handle.

As best I can remember, the only time I have wanted to be able to define
a non-anonymous function from the command line was when someone had
posted a question containing a function and I didn't feel like taking
the time to write it in to a file.

Other than that, my needs would be met if Mathworks could provide an
equivalent of the ternary ?: operator, with the ?: being nestable and
usable within anonymous functions.

Subject: Reasons for which functions are not allowed within scripts?

From: per isakson

Date: 27 Jan, 2011 22:39:04

Message: 46 of 47

Greg Heath <heath@alumni.brown.edu> wrote in message <d182b6e2-f0ce-4cbb-a7bd-a1d631aa6283@r29g2000yqj.googlegroups.com>...
> On Dec 13 2010, 2:31 pm, "Andrea Tagliasacchi"
> <andrea.tagliasac...@gmail.com> wrote:
> > Hello everybody,
> >
> > I am going to describe something that bugs me a lot in matlab:
> > "The inability of defining functions within scripts"
> -----SNIP
> > Any thought?
> > I think this would be something that it is about time
> > to allow MATLAB users to do!
>
> My workaround is stored in file myplotexample.m
> with contents
>
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>
> function [X, Y, Z1, Z2] = myplotexample;
> [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> Z1 = X .*sin(3*(+X.^2 - Y.^2));
> Z2 = X .* exp(-X.^2 - Y.^2);
> figure, myplot(X,Y,Z1);
> figure, myplot(X,Y,Z2);
>
> function myplot(X,Y,Z)
> f = gcf;
> p = surf(X,Y,Z);
> axis off;
> set(p,'edgecolor','none');
> camlight;
> set(p,'faceLighting','phong')
> set(f,'color','white');
> hold on;
> colormap('hot');
> [Zmin,IMIN] = min(Z(:));
> [Zmax,IMAX] = max(Z(:));
> plot3(X(IMIN),Y(IMIN),Z(IMIN),'*r','markersize',20);
> plot3(X(IMAX),Y(IMAX),Z(IMAX),'*b','markersize',20);
>
> return
>
> close all; clear all; clc;
> [X, Y, Z1, Z2] = myplotexample;
> whos
>
> % whos
> % U = ans;
> % [X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
> % isX = isequal(U,X)
>
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>
> 1. When I cut and paste the three lines below "return",
> into the command line everything is OK
> 2. When I open the file and click on debug/run
>
> a. The plots are OK
> b. I do not see the result of whos
> c. Something is printed to the screen.
> d. When I type "whos" into the command line I see
> only 1 variable named ans with the same size as
> X,Y, Z1 and Z2.
> e. Setting U = ans and recreating X,I find that
> U = X (See the commented code at the end).
>
> However, I do not know where U is coming from.
>
> 3. I get the same results when I type "myplotexample"
> into the command line
> Comments?
> Greg

I would like use multi-line-comments to rewrite your code:

function [X, Y, Z1, Z2] = myplotexample
%{
 close all; clear all; clc;
 [X, Y, Z1, Z2] = myplotexample;
 whos
%}
[X,Y] = meshgrid(-1:.01:+1,-1:.01:1);
%<snip the rest of code>
end

function myplot(X,Y,Z) % subroutine
%<snip the code>
end

The behavior remains the same. This gives a green m-lint box and it is "better code". I think the "end" serve a purpose indicating to programmers where the function ends. When I saw your code I first thought that myplot was a nested function. Matlab might not need it.

I often add examples and other code in %{ }% and execute it with <Select> and <Execute Selection>. That is handy.

I cannot reproduce your problem 2 c. and d. in R2010b.

/ per

Subject: Reasons for which functions are not allowed within scripts?

From: aslak grinsted

Date: 1 Feb, 2011 07:21:03

Message: 47 of 47


> I also question whether there's sufficient demand for this feature -- I
> don't remember the last time someone asked for this functionality.
>

Steve, I vote for this feature. It would be really nice to have in teaching contexts. For example if you want to have a short script which calls the odesolvers or fminsearch. At the moment I use scripts ahnd @-notation as much as possible, but at some point you hit the ceiling. I propose that the functions in scripts are handled similar to @-functions. The scoping-rules would be the same.

(On a similar note: I would like to have be able to define several classes within a single m file. The sub-classes would ofcourse have limited scope and could only be constructed from within the main class.)

Tags for this Thread

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.

Contact us