From PrattWiki
Jump to: navigation, search

MATLAB has a feature that lets you put code inside a text file that MATLAB can then access and run as if the code were typed into the command line. This is fundamentally different from a user-defined function in MATLAB in several ways. First, the code in the script can "see" the workspace - that is, variables defined at the time the script runs are defined inside the script, and any changes made inside the script are reflected in the workspace when the script finishes. Second, variables cannot be passed to the script.

This structure is good for writing the "big picture" code that coordinates all the computational tasks. Scripts can have inline functions and anonymous functions defined within them and can also call on any user-defined functions or other scripts that the script "sees" in its path.


To create a script, all you have to do is edit a text file whose name starts with a letter, contains letters and numbers (and possibly the underscore character), and ends in .m - also, the script cannot start with something resembling

function [OUT1, OUT2, ...] = FNAME(IN1, IN2, ...)

because then MATLAB would interpret that file as a user-defined function instead of a script.

MATLAB Help File

Part of the MATLAB help file for scripts is[1]

 SCRIPT About MATLAB scripts and M-files.
    A  SCRIPT file is an external file that contains a sequence
    of MATLAB statements.  By typing the filename, subsequent 
    MATLAB input is obtained from the file.  SCRIPT files have
    a filename extension of ".m" and are often called "M-files". 
    To make a SCRIPT file into a function, see FUNCTION.


  • Make sure any scripts you define no not have the same name as built-in MATLAB functions; MATLAB will look at the workspace for a name first, then your directory, then its own built-in library. Calling a script for an assignment plot.m for example is a quick way to make life very difficult for you.


Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links


  1. Quoted from MATLAB help file for script