Create Scripts - MATLAB & Simulink (original) (raw)
Main Content
Scripts are the simplest kind of code file because they have no input or output arguments. They are useful for automating series of MATLABĀ® commands, such as computations that you have to perform repeatedly from the command line or series of commands you have to reference.
You can create a new script in the following ways:
- Highlight commands from the Command History, right-click, and select .
- On the Home tab, click the New Script button.
- Use the
edit
function. For example,edit _`newfilename`_
creates (if the file does not exist) and opens the filenewfilename
. Ifnewfilename
is unspecified, MATLAB opens a new file calledUntitled
.
After you create a script, you can add code to the script and save it. For example, you can save this code that generates random numbers from 0 through 100 as a script callednumGenerator.m
.
columns = 10000; rows = 1; bins = columns/100;
rng(now); list = 100*rand(rows,columns); histogram(list,bins)
Save your script and run the code using either of these methods:
- Type the script name on the command line and press Enter. For example, to run the
numGenerator.m
script, typenumGenerator
. - On the Editor tab, click the Run button.
You also can run the code from a second code file. To do this, add a line of code with the script name to the second code file. For example, to run thenumGenerator.m
script from a second code file, add the linenumGenerator;
to the file. MATLAB runs the code in numGenerator.m
when you run the second file.
When execution of the script completes, the variables remain in the MATLAB workspace. In the numGenerator.m
example, the variablescolumns
, rows
, bins
, andlist
remain in the workspace. To see a list of variables, typewhos
at the command prompt. Scripts share the base workspace with your interactive MATLAB session and with other scripts.