MATLAB scripts add an additional level of complexity and utility over interactive mode. The most important thing about scripts is that they are called by the name of the file in which they reside. For example, if you create a file named hello.m and put the preceding 'disp' command into that file, you can then call the script from the interpreter by typing 'hello', the script name without the '.m' extension. An additional restriction on the naming of scripts is that they cannot begin with a numerical character (this is true for any variable declared in MATLAB).

File: hello.m
disp 'Hello World';
Calling the hello script

>> hello
Hello World

Arguments cannot be passed to scripts (this is the primary difference between a script and a function), so they are only able to operate on variables already defined in the interpreter. Likewise, any variables declared within a script are by default global (excepting variables declared in local functions in a script, which is possible since R2016b), that is, they may be accessed by interactive commands issued at the prompt after the script has run.

Danger: Don't use uninitialized variables in scripts

This distinction is important because using variables in scripts without first initializing them can be dangerous: the variables may have already been defined in the interpreter and therefore have unexpected values. One should always initialize any variable used in a script to a sensible value, for example 0, before calling it.

Danger: Don't overwrite global namespace variables

Script users must also be aware of the danger of overwriting variables in the global namespace which the user may have intended for other purposes. For example, suppose you are plotting data in the interpreter using the common variable name 'x', and a colleague sends you a script to perform an intermediate calculation on the data before it is plotted. If this script also happens to make use of the variable 'x' in a temporary calculation, the next plot you make will no longer have the correct axes and you may (without intimate knowledge of the workings of the script) be unsure as to the cause of the error.

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement