Skip to content Skip to navigation

OpenStax_CNX

You are here: Home » Content » Introductory Programming with MATLAB

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Introductory Programming with MATLAB

Module by: Serhat Beyenir. E-mail the author

Summary: Basic MATLAB programming concepts are presented to demonstrate how to create, save and execute script files.

Note: You are viewing an old version of this document. The latest version is available here.

ProgrammingWithMATLAB

MATLAB provides scripting and automation tools that can simplify repetitive computational tasks. For example, a series of commands executed in a MATLAB session to solve a problem can be saved in a script file called an m-file. An m-file can be executed from the command line by typing the name of the file or by pressing the run button in the built-in text editor tool bar.

Script Files

A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m. By typing the filename at the command prompt, we can run the script and obtain results in the command window.

Figure 1: Number of m-files are displayed in the Current Folder sub-window.
m-file

A sample m-file named ThermalConductivity.m is displayed in Text Editor below. Note the triangle (in green) run button in the tool bar, pressing this button executes the script in the command window.

Figure 2: The content of ThermalConductivity.m file is displayed in Text Editor.
m-file editor

Now let us see how an m-file is created and executed.

Example 1

A cylindrical acetylene bottle with a radius r=0.3 m has a hemispherical top. The height of the cylindrical part is h=1.5 m. Write a simple script to calculate the volume of the acetylene bottle.

To solve this problem, we will first apply the volume of cylinder equation. Using the volume of sphere equation, we will calculate the volume of hemisphere. The total volume of the acetylene bottle is found with the sum of volumes equation.

V cylinder = πr2h V cylinder = r 2 h
(1)
V sphere = 43 πr3 V sphere = 4 3 r 3
(2)
V top = 23 πr3 V top = 2 3 r 3
(3)
V acetylene bottle = V cylinder + V top V acetylene bottle = V cylinder V top
(4)

To write the script, we will use the built-in text editor. From the menu bar select File > New > Script. The text editor window will open in a separate window. First save this file as AcetyleneBottle.m. In that window type the following code paying attention to the use of percentage and semicolon symbols to comment out the lines and suppress the output, respectively.

% This script computes the volume of an acetylene bottle with a radius r=0.3 m, 
% a hemispherical top and a height of cylindrical part h=1.5 m.
r=0.3;                      % Radius [m]
h=1.5;                      % Height [m]
Vol_top=(2*pi*r^3)/3;       % Calculating the volume of hemispherical top [m3]
Vol_cyl=pi*r^2*h;           % Calculating the volume of cylindrical bottom [m3]
Vol_total=Vol_top+Vol_cyl   % Calculating the total volume of acetylene bottle [m3]

Figure 3: Script created with the built-in text editor.
AcetyleneBottle

After running the script by pressing the green button in the Text Editor tool bar, the output is displayed in the command window as shown below.

Figure 4: The MATLAB output in the command window.
AcetyleneBottle

The input Function

Notice that the script we have created above is not interactive and computes the total volume only for the variables defined in the m-file. To make this script interactive we will make some changes to the existing AcetyleneBottle.m by adding input function and save it as AcetyleneBottleInteractive.m.

The syntax for input is as follows:

userResponse = input('prompt')

Example 2

Now, let's incorporate the input command in AcetyleneBottleInteractive.m as shown below and the subsequent figure:

% This script computes the volume of an acetylene bottle 
    % user is prompted to enter 
        % a radius r for a hemispherical top
        % a height h for a cylindrical part
r=input('Enter the radius of acetylene bottle in meters ');                                     
h=input('Enter the height of cylindrical part of acetylene bottle in meters ');
Vol_top=(2*pi*r^3)/3;         % Calculating the volume of hemispherical top [m3]
Vol_cyl=pi*r^2*h;             % Calculating the volume of cylindrical bottom [m3]
Vol_total=Vol_top+Vol_cyl     % Calculating the total volume of acetylene bottle [m3]

Figure 5: Interactive script that computes the volume of acetylene cylinder.
AcetyleneBottle

The command window upon run will be as follows, note that user keys in the radius and height values and the same input values result in the same numerical answer as in example which proves that the computation is correct.

Figure 6: The same numerical result is obtained through interactive script.
AcetyleneBottle

The disp Function

As you might have noticed, the output of our script is not displayed in a well-formatted fashion. Using disp, we can control how text or arrays are displayed in the command window. For example, to display a text string on the screen, type in disp('Hello world!'). This command will return our friendly greeting as follows: Hello world!

disp(variable) can be used to display only the value of a variable. To demonstrate this, issue the following command in the command window:

b = [1 2 3 4 5]

We have created a row vector with 5 elements. The following is displayed in the command window:

>> b = [1 2 3 4 5]

b =

     1     2     3     4     5

Now if we type in disp(b) and press enter, the variable name will not be displayed but its value will be printed on the screen:

>> disp(b)
     1     2     3     4     5

The following example demonstrates the usage of disp function.

Example 3

Now, let's open AcetyleneBottleInteractive.m file and modify it by using the disp command. First save the file as AcetyleneBottleInteractiveDisp.m, so that we don't accidentally introduce errors to a working file and also we can easily find this particular file that utilizes the disp command in the future. The new file should contain the code below:

% This script computes the volume of an acetylene bottle 
    % user is prompted to enter 
        % a radius r for a hemispherical top
        % a height h for a cylindrical part
clc                           % Clear screen
disp('This script computes the volume of an acetylene bottle')
r=input('Enter the radius of acetylene bottle in meters ');                                     
h=input('Enter the height of cylindrical part of acetylene bottle in meters ');
Vol_top=(2*pi*r^3)/3;         % Calculating the volume of hemispherical top [m3]
Vol_cyl=pi*r^2*h;             % Calculating the volume of cylindrical bottom [m3]
Vol_total=Vol_top+Vol_cyl;    % Calculating the total volume of acetylene bottle [m3]
disp(' ')                     % Display blank line
disp('The volume of the acetylene bottle is') % Display text
disp(Vol_total)               % Display variable

Your screen output should look similar to the one below:

This script computes the volume of an acetylene bottle
Enter the radius of acetylene bottle in meters .3
Enter the height of cylindrical part of acetylene bottle in meters 1.5
 
The volume of the acetylene bottle is
    0.4807

The num2str Function

The num2str function allows us to convert a number to a text string. Basic syntax is str = num2str(A) where variable A is converted to a text and stored in str. Let's see how it works in AcetyleneBottleInteractiveDisp.m. Remember to save the file with a different name before editing it, for example, AcetyleneBottleInteractiveDisp1.m.

Example 4

Add the following line of code to your file:

str = ['The volume of the acetylene bottle is ', num2str(Vol_total), ' cubic meters.'];

Notice that the three arguments in str are separated with commas. The first argument is a simple text that is contained in ' '. The second argument is where the number to string conversion take place. And finally the third argument is also a simple text that completes the sentence displayed on the screen. Using semicolon at the end of the line suppresses the output. In the next line of our script, we will call str with disp(str);.

AcetyleneBottleInteractiveDisp1.m file should look like this:

% This script computes the volume of an acetylene bottle 
  % user is prompted to enter 
        % a radius r for a hemispherical top
        % a height h for a cylindrical part
clc                           % Clear screen
disp('This script computes the volume of an acetylene bottle:')
disp(' ')                     % Display blank line
r=input('Enter the radius of acetylene bottle in meters ');                                     
h=input('Enter the height of cylindrical part of acetylene bottle in meters ');
Vol_top=(2*pi*r^3)/3;         % Calculating the volume of hemispherical top [m3]
Vol_cyl=pi*r^2*h;             % Calculating the volume of cylindrical bottom [m3]
Vol_total=Vol_top+Vol_cyl;    % Calculating the total volume of acetylene bottle [m3]
disp(' ')                     % Display blank line
str = ['The volume of the acetylene bottle is ', num2str(Vol_total), ' cubic meters.'];
disp(str);

Running the script should produce the following:

This script computes the volume of an acetylene bottle:
 
Enter the radius of acetylene bottle in meters .3
Enter the height of cylindrical part of acetylene bottle in meters 1.5
 
The volume of the acetylene bottle is 0.48066 cubic meters.

The diary Function

Instead of writing a script from scratch, we sometimes solve problems in the Command Window as if we are using a scientific calculator. The steps we perform in this fashion can be used to create an m-file. For example, the diary function allows us to record a MATLAB session in a file and retrieve it for review. Reviewing the file and by copying relevant parts of it and pasting them in to an m-file, a script can be written easily.

Typing diary at the MATLAB prompt toggles the diary mode on and off. As soon as the diary mode is turned on, a file called diary is created in the current directory. If you like to save that file with a specific name, say for example problem16, type diary ('problem16'). A file named problem16 will be created. The following is the content of a diary file called problem16. Notice that in that session, the user is executing the four files we created earlier. The user's keyboard input and the resulting display output is recorded in the file. The session is ended by typing diary which is printed in the last line.

AcetyleneBottle

Vol_total =

    0.4807

AcetyleneBottleInteractive
Enter the radius of acetylene bottle in meters .3
Enter the height of cylinderical part of acetylene bottle in meters 1.5

Vol_total =

    0.4807

AcetyleneBottleInteractiveDisp
This script computes the volume of an acetylene bottle
Enter the radius of acetylene bottle in meters .5
Enter the height of cylinderical part of acetylene bottle in meters 1.6
 
The volume of the acetylene bottle is
    1.5184

AcetyleneBottleInteractiveDisp1
This script computes the volume of an acetylene bottle:
 
Enter the radius of acetylene bottle in meters .9
Enter the height of cylinderical part of acetylene bottle in meters 1.9
 
The volume of the acetylene bottle is 6.3617 cubic meters.
diary

Style Guidelines

Try to apply the following guidelines when writing your scripts:

  • Share your code or programs with others, consider adopting one of Creative Commons or GNU General Public License schemes
  • Include your name and contact info in the opening lines
  • Use comments liberally
  • Group your code and use proper indentation
  • Use white space liberally
  • Use descriptive names for your variables
  • Use descriptive names for your m-files

Summary of Key Points

  1. A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m.
  2. Functions such as input, disp and num2str can be used to make scripts interactive,
  3. diary function is useful to record a MATLAB command window session from which an m-file can be easily created,
  4. Various style guidelines covered here help improve our code.

Content actions

Download module as:

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks