Session 1: MATLAB Functions and Scripts

Date: 09/11/2017, Monday

In [1]:
format compact

MATLAB’s function control can be somewhat confusing… Let me try to explain it.

3 ways to execute MATLAB codes

You can run MATLAB codes in these ways:

  • Executing codes directly in the interactive console
  • Put codes in a script (an m-file), and execute the script in the console
  • Put codes in a function (also an m-file), and execute the function in the console

Executing codes directly

You know how to run the codes in the interactive console:

In [2]:
a=1;
b=2;
2*a+5*b
ans =
    12

To avoid re-typing the formula 2*a+5*b over and over again, you can create an inline function in the interative environment.

In [3]:
f = @(a,b) 2*a+5*b
f =
  function_handle with value:
    @(a,b)2*a+5*b
In [4]:
f(1,2)
f(2,3)
ans =
    12
ans =
    19

Writing a script

A script simply allows you to execute many lines of codes at once. It is not a function. There’s no input and output variables.

To open a new script, type “edit” in the console or click on the “New” Button.

In [5]:
edit

Save the following code into a file with the suffix “.m”

In [6]:
%%file my_script.m
a=1;
b=2;
2*a+5*b
Created file '/Users/zhuangjw/Research/Computing/personal_web/AM111/docs/my_script.m'.

Execute the script by typing its file name in the console. Make sure your working directory is the same as the script’s directory.

In [7]:
my_script
ans =
    12

You can definitely change parameters a, b in your script and re-run the script over and over again. However, to have a better control on input arguments, you need to write a function, a not script.

Writing a function

A function is also a file with the suffix “.m”, same as a script. But it contains the function head which defines input and output parameters. The function name has to be the same as the file name.

In [8]:
%%file my_func.m
function s=my_func(a,b)
    s = 2*a+5*b;
end
Created file '/Users/zhuangjw/Research/Computing/personal_web/AM111/docs/my_func.m'.

Now you can provide input arguments to your function.

In [9]:
my_func(1,2)
ans =
    12

Multi-level functions

An m-file can contain multiple functions. But only the first one can be accessed from the outside. Others are only for internal use.

In [10]:
%%file mul_by_4.m

function z=mul_by_4(x)
    y = mul_by_2(x);
    z = mul_by_2(y);
end

function y=mul_by_2(x)
    y = 2*x;
end
Created file '/Users/zhuangjw/Research/Computing/personal_web/AM111/docs/mul_by_4.m'.

You can call mul_by_4( ), but cannot call mul_by_2( ).

In [11]:
mul_by_4(2)
ans =
     8
In [12]:
mul_by_2(2)
Error using eval
Undefined function 'mul_by_2' for input arguments of type 'double'.

Note: Since R2016b, you can also add functions in scripts. However, you had better avoid this usage for backward capability. Otherwise, people using an older version of MATLAB will have trouble running your code. Always create a separate file for your function.