MATLAB Programming/Scripts
M-files
[edit | edit source]There are 2 types of m-file
- Scripts
- Functions
Scripts are a type of m-file that runs in the current workspace. So if you call a script from the command line (base workspace) the script will use and manipulate the variables of the base workspace. This can get very messy and lead to all sorts of strange errors when loops are involved and the coder is lazy about naming their loop variables (i.e. for i = 1:10, if every loop uses i, j, or k then it's likely that any script called from a loop will alter the loop variable).
Functions are wholly contained in themselves. They possess their own workspace keeping workspaces separate. This means that all variables necessary for a particular function must be passed or defined in some way. This can get tedious for complex algorithms requiring lots of variables. However, any manipulations of variables are discarded when the function is exited. Only those output arguments provided by the function are available to the calling workspace. This means that loops can use i, j, or k all they want because the function's workspace and the calling workspace do not mix.
Any command valid at the command line is valid in any m-file so long as the necessary variables are present in the m-files operating workspace.
Using functions properly any change can be affected to any algorithm or plotting tool. This allows for automation of repetitive tasks.
It is optional to end the M-file with 'end'; doing so, however, can lead to complications if you have conditionals or loops in your code, or if you're planning on using multiple functions in the same file (see nested functions for details on this).
Requirements for a function
[edit | edit source]Custom functions follow this syntax in their most basic form:
function [output1, output2, ...]= function_name(input_arg1,input_arg2) statements return;
In current versions of MATLAB the return; line is not required. The function_name can be anything you like but it is best if the m-file name is function_name.m. Calling the function from the command line or another m-file is done by invoking the m-file name of the function with the necessary input and output arguments.
Within the function itself, there must be a statement that defines each of the output arguments (output1, output2, etc.). Without some declaration the variable for the output argument doesn't exist in the function's workspace. This will cause an error about "one or more output arguments". It is good practice to initialize the output arguments at the beginning of the function.
Typically output arguments are initialized to empty ([]) or 0 or -1 or something equivalent for other data types. The reason is that if the function encounters an error you've anticipated then the function can return (via the return command) with those default values. If the initialization value is an invalid value then it can easily be checked by the calling function for any errors which may not throw a MATLAB error.
Path
[edit | edit source]In order to invoke a function, that function's m-file must be in the current path. There is a default path that can be set up through the File menu or the addpath command. The order of the path is important as MATLAB searches the path in order and stops searching after it finds the first instance of that m-file name.
The current path is
- the current directory (which can be seen at the top of the MATLAB window or by typing pwd at the command prompt
- the default path
Note that MATLAB will always search the current directory before searching any of the rest of the path.
nargin & nargout
[edit | edit source]The nargin and nargout commands are only valid inside functions since scripts are not passed any arguments. The nargin command returns the number of passed input arguments. This is useful in conjunction with nargchk
nargchk(min, max, nargin)
where min is the minimum number of arguments necessary for the function to operate and max is the maximum number of valid input arguments.
The nargout command is useful for determining which output arguments to return. Typically, the outputs are the end results of some algorithm and they are easily calculated. However, in some instances secondary output arguments can be time consuming to calculate or require more input arguments than the primary output arguments do. So the function can check the number of output arguments being requested through the nargout command. If the caller isn't saving the secondary output arguments then they do not need to be calculated.
varargin & varargout
[edit | edit source]When using MATLAB objects and functions they often allow the user to set properties. The functions and objects come with default values for these properties but the user is allowed to override these defaults. This is accomplished through the use of varargin. varargin is a cell array that is usually parsed where varargin{i} is a property and varargin{i+1} is the value the user wishes for that property. The parsing is done with a for or while loop and a switch statement.
function [out] = myFunc(in, varargin)
The varargout output argument option allows for a variable number of output arguments just as varargin allows for a variable number of input arguments. From the MATLAB site
function [s,varargout] = mysize(x) nout = max(nargout,1)-1; s = size(x); for k=1:nout, varargout(k) = {s(k)}; end
returns the size vector and, optionally, individual sizes. So
[s,rows,cols] = mysize(rand(4,5));
returns s = [4 5], rows = 4, cols = 5.
Useful syntax guidelines
[edit | edit source]Placing the semicolon symbol after every line tells the compiler not to place that line of code in the command prompt and then execute. This can make your programs run a lot faster. Also, placing a semicolon after every line helps with the debugging process.
syms x y z; w=[x y z]; e=[1 2 3]; t=jacobian(e,w);
Placing comments in your code can help other people (and yourself) understand your code as it gets more complex.
syms x y z; %syms command makes x y and z symbolic w=[x y z]; e=[1 2 3]; t=jacobian(e,w);
Comments can also Identify who wrote the code and when they wrote it.
%Some code writer %mm/dd/yyyy
See the 'comments' section for more details on this.
Nested functions
[edit | edit source]
External Links
[edit | edit source]Large parts of this page come from the ControlTheoryPro.com page on M-files, Scripts, and Functions.