How to Write Your First MATLAB Script - dummies

How to Write Your First MATLAB Script

By Jim Sizemore, John Paul Mueller

MATLAB provides many different ways to write scripts. Some of them don’t actually require that you write anything at all! However, the traditional way to create a script in any application is to write it. The most common first script in the entire world is the “Hello World” example. The following steps demonstrate how to create such a script using MATLAB.

1Click New Script on the Home tab of the menu.

You see the Editor window appear. This window provides the means to interact with scripts in various ways. This Editor tab is the one you use most often when creating new scripts.

2Type’Hello World’.

The text is highlighted in a light orange, and a squiggly red line appears under it. When you hover your mouse over the squiggly line, you see an error message.

In this case, you ignore the error because you want to see the output. However, if you wanted to correct the problem (the way MATLAB thinks you should), you could either type a semicolon or click Fix to resolve the issue. MATLAB will always tell you if it thinks that you’re making a mistake, but sometimes MATLAB is overzealous (as in this situation).

3Click Run on the Editor tab of the Editor window.

You see a Select File for Save As dialog box. MATLAB always requests that you save your script before you run it to ensure that your script doesn’t get lost or corrupted in some way should something happen when it runs.

4Create your directory, type FirstScript.m in the File Name field, and click Save.

MATLAB saves your script to disk. All your script files will have an .m extension.

At this point, you may see a MATLAB Editor dialog box appear. If that happens, simply click the box’s Add to Path button to make the dialog box disappear. If you don’t see this box, continue to Step 5.

5Select the MATLAB window.

You see the following script output:

>> FirstScript
ans =
Hello World

The output is telling you that MATLAB has run FirstScript, which is the name of the file containing the script, and that the output is Hello World. This output has been assigned to ans, the default variable.