From ControlTheoryPro.com

Jump to: navigation, search
Green carrot left.gif
MATLAB Scripts MATLAB Functions
Green carrot.jpg
In order to prevent spam, users must register before they can edit or create articles.

1 M-files

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 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 variable 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).

2 Useful syntax guidelines

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];

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];

Comments can also Identify who wrote the code and when they wrote it.

%Some code writer

See the 'comments' section for more details on this.