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.
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”.
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.
fprintf('Hello World') %Write the ‘Hello World’ codeCommand Window Output
Hello World [Try this code yourself with Octave Online! Click Here]
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).
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).
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.
%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]
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.