Skip to content Skip to navigation Skip to collection information

OpenStax-CNX

You are here: Home » Content » A Brief Introduction to Engineering Computation with MATLAB » Writing Scripts to Solve Problems

Navigation

Table of Contents

Recently Viewed

This feature requires Javascript to be enabled.
 

Writing Scripts to Solve Problems

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.

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 fopen and fclose Functions

The first command is used to open or create a file. The basic syntax for fopen is as follows:

fid = fopen(filename, permission)

For example, fo = fopen('output.txt', 'w'); opens or creates a new file named output.txt and sets the permission for writing. If the file already exists, it discards the existing contents.

fclose command is used to close a file. For example, if we type in fclose(fo);, we close the file that was created above.

The fprintf Function

fprintf function writes formatted data to the computer monitor or a file. This command can be used to save the results of a calculation to a file. To do this, first we create or open an output file with fopen, second we issue the fprintf command and then we close the output file with fclose.

The simplified syntax for fprintf is as follows:

fprintf=(fid, format, variable1, variable 2, ...)

Example 5

Add the following lines to your .m file:

fo = fopen('output.txt', 'w');
fprintf(fo,'The radius of acetylene bottle: %g meters \n', r);
fprintf(fo,'The height of cylindrical part of acetylene bottle: %g meters \n', h);
fprintf(fo,'The volume of the acetylene bottle: %g cubic meters. \n', Vol_total);
fclose(fo);

Here, we first create the output.txt file that will contain the following three variables r, h and Vol_total. In the fo output file, the variables are formated with %g which automatically uses the shortest display format. You can also use %i or %d for integers and %e for scientific notation. In our script above, the \n (newline) moves the cursor to the next line.

Naming the new .m file as AcetyleneBottleInteractiveOutput.m, it 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);
fo = fopen('output.txt', 'w');
fprintf(fo,'The radius of acetylene bottle: %g meters \n', r);
fprintf(fo,'The height of cylindrical part of acetylene bottle: %g meters \n', h);
fprintf(fo,'The volume of the acetylene bottle: %g cubic meters. \n', Vol_total);
fclose(fo);

Upon running the file, the output.txt file will display the following:

The radius of acetylene bottle: 0.3 meters 
The height of cylindrical part of acetylene bottle: 1.5 meters 
The volume of the acetylene bottle: 0.480664 cubic meters.

Loops

In programming, a loop executes a set of code a specified number of times or until a condition is met.

For Loop

This loop iterates an index variable from an initial value using a specified increment to a final value and runs a set of code. The for loop syntax is the following:


    for loop_index=vector_statement
      code
      ...
      code
    end

Example 6

Calculate y=cosxyx for πxπx using an increment of π44.


for x=-pi:pi/4:pi       
    y=cos(x);           
    fprintf('%8.3f %8.2f \n',x,y); 
end

In the brief script above, xx is the loop index that is initiated from π and incremented with π44 to a final value of π. At the end of each increment, y=cosxyx is calculated and displayed with the fprintf command. This process continues until x=πx.

From a previous exercise we know \n creates a new line when included in the fprintf command. Here, we also use %8.3f to specify eight spaces and three decimal places for the first variable x. Likewise %8.2f specifies the formatting for the second variable y but in this case, y is displayed with two decimal places. The result is the following:


  -3.142    -1.00 
  -2.356    -0.71 
  -1.571     0.00 
  -0.785     0.71 
   0.000     1.00 
   0.785     0.71 
   1.571     0.00 
   2.356    -0.71 
   3.142    -1.00

We can improve our code by adding formatting lines as follows:


clear; clc;
fprintf('   x         cos(x)\n') % title row
fprintf('   ----------------\n') % title row
 for x=-pi:pi/4:pi       % loop_index=inital_value:increment_value:final_value
    y=cos(x);           % code to calculate cos(x)
    fprintf('%8.3f %8.2f \n',x,y); % code to print the output to screen
 end

Screen output:


   x         cos(x)
   ----------------
  -3.142    -1.00 
  -2.356    -0.71 
  -1.571     0.00 
  -0.785     0.71 
   0.000     1.00 
   0.785     0.71 
   1.571     0.00 
   2.356    -0.71 
   3.142    -1.00

While Loop

Like the for loop, a while loop executes blocks of code over and over again however it runs as long as the test condition remains true. The syntax of a while loop is


    while test_condition
     code
     ...
     code
    end 

Example 7

Using a while loop, calculate y=cosxyx for πxπx using an increment of π44.

This time we need to initialize the x value outside the loop and then state the test condition in the first line of the while loop. We also need to create an increment statement within the while loop:


x=-pi;
    while x<=pi     
        y=cos(x); 
        fprintf('%8.3f %8.2f \n',x,y); 
        x = x + (pi/4);                   
    end

The result is the same as that of the previous example:


  -3.142    -1.00 
  -2.356    -0.71 
  -1.571     0.00 
  -0.785     0.71 
   0.000     1.00 
   0.785     0.71 
   1.571     0.00 
   2.356    -0.71 
   3.142    -1.00

Now we can improve the code adding extra formatting lines:


clear; clc;
fprintf('   x         cos(x)\n') % title row
fprintf('   ----------------\n') % title row
x=-pi;
while x<=pi     
    y=cos(x); 
            fprintf('%8.3f %8.2f \n',x,y); 
            x = x + (pi/4);                   
end

The result should look the same as before.


   x         cos(x)
   ----------------
  -3.142    -1.00
  -2.356    -0.71
  -1.571     0.00
  -0.785     0.71
   0.000     1.00
   0.785     0.71
   1.571     0.00
   2.356    -0.71
   3.142    -1.00

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.txt.
A file named problem16.txt will be created. The following is the content of a diary file called problem16.txt. 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. This might be useful to create a record of your work to hand in with a lab or to create the beginnings of an m-file.

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. fopen, fprintf and fclose functions are used to create output files,
  4. A for loop is used to repeat a specific block of code a definite number of times.
  5. A while loop is used to repeat a specific block of code an indefinite number of times, until a condition is met.
  6. The diary function is useful to record a MATLAB command window session from which an m-file can be easily created,
  7. Various style guidelines covered here help improve our code.

Collection Navigation

Content actions

Download:

Collection as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add:

Collection 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

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