8.5. MATLAB programs#

We have used the console for a while now and you may start to notice that it has some shortcomings. For example, if you want to change the value of a variable, any other commands that use that variable will need to be entered again. This is where programs are useful. A program is a file or a collection of files that contain Python commands that can be run.

In MATLAB create a new file:

  1. Click on New Script icon in the top left hand corner of the MATLAB window. This will open up an Editor window with the title untitled.

  2. Click on the Save icon, navigate to the folder where you want to save the program (e.g., Documents/Programming_skills/) and give it the filename M1_MATLAB_basics.py (MATLAB script filenames must start with a letter).

We are going to write a simple program that converts an angle expressed in degrees to radians. In your M1_Python_basics.py file enter the following code (you can leave the text at the top of the file).

angle_in_degrees = 45;
angle_in_radians = angle_in_degrees * pi / 180;
angle_in_radians

The first three lines should be familiar to you as we have declared the variable angle_in_degrees which is used to calculate the value of angle_in_radians. Note that the value of pi is already built into MATLAB. Run the program by clicking on the run button or by pressing the F5 key, you should see the following output added to the command window.

>> M1_MATLAB_basics

angle_in_radians =

    0.7854

8.5.1. Clearing workspaces#

A common source of errors when programming in MATLAB is when your are reusing variables that have been defined previously. For this reason it is good practice to clear all variables from the memory when starting a new program. This can be done using the clear command. Try it out by entering it into the command window. You should see that the Workspace area on the right hand side of the MATLAB window is now empty.

As a rule you should always start a MATLAB program with the following commands.

clear % Clear all variables
clc   % Clear command window

8.5.2. Exercise#

Create a new MATLAB file called M1_MATLAB_basics_exercises.py and save it to your OneDrive folder. Use it to answer the remaining exercises in this chapter.

Exercise 8.4

Write a program similar to Exercise 8.2 except that it converts a temperature from degrees Fahrenheit to degrees Centigrade and outputs the result to the console.

Convert the following to degrees Centigrade:

  1. 100 \(^\circ\)F

  2. 0 \(^\circ\)F