In MATLAB, can I have a script and a function definition in the same file?

99,673

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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.

Solution 5

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

x = 1;
y = add1(x);

function z = add1(x)
    z = x + 1;
end
Share:
99,673

Related videos on Youtube

Viktor
Author by

Viktor

Updated on August 22, 2020

Comments

  • Viktor
    Viktor over 3 years

    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.

    • Jeremiah Willcock
      Jeremiah Willcock about 13 years
      Note that you can put functions in scripts in Octave.
    • Londerson Araújo
      Londerson Araújo about 11 years
      Consider this answer for ways to organize your code stackoverflow.com/a/3569946/18775
    • URL87
      URL87 almost 11 years
      Very recommend to take a look at stackoverflow.com/questions/17315586/…
    • drysdam
      drysdam over 8 years
      The real question should be: Who at Mathworks do I complain to to get this ridiculous bug fixed?
    • onewhaleid
      onewhaleid over 7 years
      As of MATLAB 2016b, functions can be defined in scripts. I am not sure why they waited 32 years to add this fairly basic feature.
  • Bi Rico
    Bi Rico over 12 years
    +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.
  • marcelocra
    marcelocra over 9 years
    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).
  • James Taylor
    James Taylor about 9 years
    Can you please include a sample implementation of this "hack"? I can't seem to figure out how this works.
  • chessofnerd
    chessofnerd over 8 years
    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.
  • John
    John over 8 years
    @chessofnerd When I have the problem, I either return the variables in the function output, or I use assignin.
  • chessofnerd
    chessofnerd over 8 years
    @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!
  • John
    John over 8 years
    @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."
  • sancho.s ReinstateMonicaCellio
    sancho.s ReinstateMonicaCellio about 8 years
    Is this different from the answer by John?