84

Suppose I have a function f() and I want to use it in my_file.m, which is a script.

  1. Is it possible to have the function defined in my_file.m?
  2. If not, suppose I have it defined in f.m. How do I call it in my_file.m?

I read the online documentation, but it wasn't clear what is the best way to do this.

Mike Polen
  • 3,586
  • 1
  • 27
  • 31
Viktor
  • 841
  • 1
  • 6
  • 3

7 Answers7

50

As of release R2016b, you can have local functions in scripts, like so:

data = 1:10;            % A vector of data
squaredData = f(data);  % Invoke the local function

function y = f(x)
  y = x.^2;
end

Prior to release R2016b, the only type of function that could be defined inside a MATLAB script was an anonymous function. For example:

data = 1:10;            % A vector of data
f = @(x) x.^2;          % An anonymous function
squaredData = f(data);  % Invoke the anonymous function

Note that anonymous functions are better suited to simple operations, since they have to be defined in a single expression. For more complicated functions, you will have to define them in their own files, place them somewhere on the MATLAB path to make them accessible to your script, and then call them from your script as you would any other function.

gnovice
  • 125,304
  • 15
  • 256
  • 359
38

The way I get around this limitation, is to turn my scripts into functions that take no arguments (if I need variables from the global namespace, I either explicitly pass them in the function, or use "evalin" to grab them.)

Then you can define all the additional functions you need in the "script." It's a hack, but I have found it to be quite powerful in those cases where I need several non-trivial functions.

EDIT: Here's a simplistic example. All this can reside in a single file.

function [] = myScriptAsAFunction()
   img = randn(200);
   img = smooth(img);
   figure(1);
   imagesc(img);
   axis image;
   colorbar;
end

function simg = smooth(img)
    simg = img / 5;
end
John
  • 5,735
  • 3
  • 46
  • 62
  • 6
    +1, it really annoys me when I see clear all; close all; at the top of a matlab script. If you have so many variables and plots floating around you can't keep track of them you're not using enough functions. – Bi Rico Feb 07 '12 at 00:11
  • 1
    Can you please include a sample implementation of this "hack"? I can't seem to figure out how this works. – James Taylor Apr 02 '15 at 14:08
  • 1
    Note one problem with this approach is that the variables never make it into your workspace when the function exits. This can be a problem if you want to play/look/use those variables upon the end of the script. – chessofnerd Sep 09 '15 at 23:57
  • 1
    @chessofnerd When I have the problem, I either return the variables in the function output, or I use assignin. – John Sep 10 '15 at 15:50
  • 1
    @John, I personally feel that is a bit of a pain to have to return all variables individually as opposed to having them show up in the work space on their own. That said, I had never heard of `assignin`. That is a neat function that I might be using more! – chessofnerd Sep 10 '15 at 21:25
  • 1
    @chessofnerd I have recently adopted the practice of returning complex outputs of a function in a structure. This has cleaned up my parameter lists immensely and makes interfaces much more "future proof." – John Jan 26 '16 at 14:02
20

You can do something like this (assuming your file is named my_file.m):

function my_file
   %script here
end

function out = f(in)
   %function here
end

If you click the run button the function my_file will be executed as default.

Oneiros
  • 4,328
  • 6
  • 40
  • 69
7

As of R2016b, you can define local functions within a script.

x = 1;
y = add1(x);

function z = add1(x)
    z = x + 1;
end
Suever
  • 64,497
  • 14
  • 82
  • 101
7

1) You cannot nest a function inside a script.

2) Make sure f.m is on your path or in current directory, and you can call it like any other function.

Rich C
  • 3,164
  • 6
  • 26
  • 37
  • You can nest a function inside a script if you follow what is proposed by @Oneiros. You can even call your function (`f` in his example) from within your script (`my_file` in his example). – marcelocra Oct 17 '14 at 14:34
3

I have implemented the solution by John, and I found it useful. But there are a couple of caveats (in Octave; Matlab possibly behaves similarly):

  1. If code inside your main function contains clear all prior to using the auxiliary function, it will not work. In file test3.m, commenting/uncommenting clear all makes code work/not work.

    function [] = test3()
      %clear all
      a = myfunc( 1 );
      a
    endfunction;
    
    %---------------------------------
    % Auxiliary functions
    
    function retval = myfunc( a )
      retval = 2 * a;
    endfunction;
    

    From It seems like upon running a script, there is a first pass where code outside functions is executed (in this case, there is no such code), and functions defined (in this case, test3 and myfunc) are added to the workspace. A second pass would execute the main function, which would not find myfunc if clear all is active.

  2. As pointed out by chessofnerd, out-of-the-box the variables in your main function do not go to the workspace.

Community
  • 1
  • 1
2

You can have many functions in a sample file. But only the first one can act as a main function, when you run the file. Others can be used merely in this file. For some situation you want to define a big function. You can separate it into smaller functions and define below it.

However, the most simple way to find the answer is having a try~