# MATLAB Programming/Scripts

[MATLAB Programming\|/MATLAB Programming]m]
Chapter 1: MATLAB ._.
    Fundamentals of MATLAB
    MATLAB Workspace
    MATLAB Variables
    *.mat files
Chapter 2: MATLAB Concepts
    MATLAB operator
    Data File I/O
Chapter 3: Variable Manipulation
    Numbers and Booleans
    Strings
    Portable Functions
    Complex Numbers
Chapter 4: Vector and matrices
    Vector and Matrices
    Special Matrices
    Operation on Vectors
    Operation on Matrices
    Sparse Matrices
Chapter 5: Array
    Arrays
    Introduction to array operations
    Vectors and Basic Vector Operations
    Mathematics with Vectors and Matrices
    Struct Arrays
    Cell Arrays
Chapter 6: Graphical Plotting
    Basic Graphics Commands
    Plot
    Polar Plot
    Semilogx or Semilogy
    Loglog
    Bode Plot
    Nichols Plot
    Nyquist Plot
Chapter 7: M File Programming
    Scripts
    Comments
    The Input Function
    Control Flow
    Loops and Branches
    Error Messages
    Debugging M Files
Chapter 8: Advanced Topics
    Numerical Manipulation
    Advanced File I/O
    Object Oriented Programming
    Applications and Examples
    Toolboxes and Extensions
Chapter 9: Bonus chapters
    MATLAB Benefits and Caveats
    Alternatives to MATLAB
    [MATLAB_Programming/GNU_Octave|What is Octave= (8) hsrmonic functions]
    Octave/MATLAB differences

## 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 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

Custom functions follow this syntax in their most basic form:
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

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

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

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.
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
returns the size vector and, optionally, individual sizes. So
returns s = [4 5], rows = 4, cols = 5.

## 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.
Placing comments in your code can help other people (and yourself) understand your code as it gets more complex.
Comments can also Identify who wrote the code and when they wrote it.
See the 'comments' section for more details on this.

## External Links

Large parts of this page come from the ControlTheoryPro.com page on M-files, Scripts, and Functions.