This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Create Scripts

Scripts are the simplest kind of program 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 Create Script.

  • Click the New Script button on the Home tab.

  • Use the edit function. For example, edit new_file_name creates (if the file does not exist) and opens the file new_file_name. If new_file_name is unspecified, MATLAB opens a new file called Untitled.

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 between 0 and 100 as a script called numGenerator.m.

columns = 10000;
rows = 1;
bins = columns/100;

list = 100*rand(rows,columns);

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, type numGenerator.

  • Click the Run button on the Editor tab

You also can run the code from a second program file. To do this, add a line of code with the script name to the second program file. For example, to run the numGenerator.m script from a second program file, add the line numGenerator; 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 variables columns, rows, bins, and list remain in the workspace. To see a list of variables, type whos at the command prompt. Scripts share the base workspace with your interactive MATLAB session and with other scripts.

Related Topics

Was this topic helpful?