Session 1: MATLAB Functions and Scripts¶
Date: 09/11/2017, Monday
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:
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.
f = @(a,b) 2*a+5*b
f = function_handle with value: @(a,b)2*a+5*b
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.
Save the following code into a file with the suffix “.m”
%%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.
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
function head which defines input and output
parameters. The function name has to be the same as the file name.
%%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.
ans = 12
An m-file can contain multiple functions. But only the first one can be accessed from the outside. Others are only for internal use.
%%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( ).
ans = 8
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.