Create Scripts

Creating scripts, or m-files in Matlab, is the preferred and fastest method for performing repeated operations.  Whereas all of the following functions and commands can be typed directly into the command window, you might find it useful to save a sequence of commands into a pre-defined script that can be accessed again and again.

Once a new m-file is created, you are free to enter any commands into the file.  For the following example we are going to create a function that calculates the square root of a number.  While Matlab already has a predefined function for this called “sqrt”, we will utilize this script as an example.

As you can see the function we created is called square_root.  This function takes as input the variable in and returns the variable out.  Within Matlab, the percent (%) symbol is used prior to any line for comments and shows up with green text within the editor.  The nargin function evaluates how many inputs are sent to the function, with an answer of zero returning the error: ‘need more data’.

If the title window displays an asterisk (*) as shown in this image, it means the file has not been saved and changes have been made.  Be wary of this, as this is one of the first places to look when debugging.  The square_root.m file was in this case saved on the desktop, and in order to test this, we will need to point Matlab to the location of this file.  This can be done by setting the appropriate path within Matlab’s command window.  Be careful that you use addpath instead of setpath.

 >> addpath('C:\Documents and Settings\Vipul\Desktop\')

Note: the “>>” symbol is used to indicate that commands are being run in the command window.  To verify that the path has been added, run the following:

 >> path

Now test your code by evaluating the square root of 729:

 >> value=square_root(729)

Voila! The answer is 27. As you can see in the workspace, the variable value now has the number 27 stored. You can readily access the number at any time by typing value next to command prompt.  One beauty of using functions is that you have separate workspaces in use.  While we specified in and out within the script square_root.m, we can utilize any name we want when calling the function.  In this case we used value and 729, but you always want to utilize variable names that make sense, are easy to follow when we review the code several months later and are not previously defined by Matlab.  In order to check for built-in functions use the following command.

>> which sin

One way to suppress output of any script or function is to add a semicolon (;) following the command.  In addition you can evaluate the function without using the value variable.  In this case Matlab will store the answer in a temporary variable called ans.

>> square_root(729)
ans =
    27
Bookmark and Share