MATLAB - Lesson 1.2

Hello World


  • See the basic steps to start a new program in MATLAB.
  • Get a simple program up and running.

This lesson walks through how to create the classic “Hello World” program. Unlike other lessons, we won’t explain much of the how or why in this lesson. You don’t need to understand what’s going on in this lesson: just observe! The purpose here is to give beginning programmers something to relate to in subsequent lessons.

Step 1: Create a New m-file

First, we need to create a file to store our program in. In the top left portion of the MATLAB screen, create a new m-file by pressing the “New Script”. Note that in many languages a script is a common term for the file that holds your code. Save the blank file as “helloWorld”.

Figure 1: Click “New Script” on the far left under the “Home” tab to open a new m-file.

Step 2: Write the ‘Hello World’ Code

In this next step, we will write the code that will output/return our message: ‘Hello World’. Note that the green text after % will be ignored and will not be executed. See Figure 2 if you aren’t sure where to type your code.

Example 1: Write a Hello World program
fprintf('Hello World') %Write the ‘Hello World’ code Command Window Output
Hello World [Try this code yourself with Octave Online! Click Here]

Figure 2: MATLAB window showing where to type your code (in Editor window).

Step 3: Run the Program

In order to get our program to do something, we need to “run” the program. Figure 2 shows the “Run” button, which you should click in order to run the program. This is located under the “Editor” tab in the toolbar (top left of screen).

Figure 3: Run the program by click the highlighted button under the “Editor” ribbon tab (top).

Once the “Run” button is pressed, the program will execute our command. The result of our code will show in the Command Window (the window on the right).

Step 4: Make Your Program a Little Fancier

Finally, we can do a couple more things to demonstrate some other simple concepts. This time we will include our name and age in the “Hello World” greeting. Again, just observe. Each of these concepts will be explained in the lessons to come.

Example 2: Write a fancier Hello World program
%Step 4: “Fancy” stuff (just copy and see how it works) name = 'Ben'; age = 24; fprintf('Hello world, I am %s. I have been on earth for %g years.',name,age) Command Window Output
Hello world, I am Ben. I have been on earth for 24 years. [Try this code yourself with Octave Online! Click Here]

Next Lesson

In the lesson, we will explain and define the MATLAB environment. That is, we will explain the various windows and sub-windows most commonly used in MATLAB.