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

Viktor picture Viktor · Mar 19, 2011 · Viewed 99k times · Source

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.

Answer

gnovice picture gnovice · Mar 22, 2011

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.