# 13.4: Writing Scripts, input(), disp(), num2str(), more

- Page ID
- 85185

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 \(\PageIndex{1}\). Number of m-files are displayed in the Current Folder sub-window.

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 \(\PageIndex{2}\). The content of `ThermalConductivity.m`

file is displayed in Text Editor.

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

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_{\text { cylinder }}=\pi r^{2} h\)

\(V_{\text { sphere }}=\frac{4}{3} \pi r^{3}\)

\(V_{\text { top }}=\frac{2}{3} \pi r^{3}\)

\(V_{\text { acetylene bottle }}=V_{\text { cylinder }}+V_{\text { top }}\)

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 and

% 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 [m^3]

Vol_cyl=pi*r^2*h; % Calculating the volume of cylindrical bottom [m^3]

Vol_total=Vol_top+Vol_cyl % Calculating the total volume of acetylene bottle [m^3]

Figure \(\PageIndex{3}\). Script created with the built-in text editor.

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

Figure \(\PageIndex{4}\). The MATLAB output in the command window.

## 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')

where 'prompt' is something like: 'Enter the radius: '

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 \(\PageIndex{5}\). Interactive script that computes the volume of acetylene cylinder.

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 the above which proves that the computation is correct.

Figure \(\PageIndex{6}\). The same numerical result is obtained through interactive script.

## 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:

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

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.

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`

.

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

Add the following lines to your .m file:

fo = fopen('output.txt', 'w');

fprintf(fo,'The radius of acetylene bottle: %g meters nn', r);

fprintf(fo,'The height of cylindrical part of acetylene bottle: %g meters nn', h);

fprintf(fo,'The volume of the acetylene bottle: %g cubic meters. nn', 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 nn', r);

fprintf(fo,'The height of cylindrical part of acetylene bottle: %g meters nn', h);

fprintf(fo,'The volume of the acetylene bottle: %g cubic meters. nn', 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`

Calculate \(y=\cos (x)\) for \(-\pi \leq x \leq \pi\) using an increment of \(\frac{\pi}{4}\) for x=-pi:pi/4:pi y=cos(x); fprintf('%8.3f %8.2f \n',x,y); end

In the brief script above, \(x\) is the loop index that is initiated from \(-\pi\) and incremented with \(\frac{\pi}{4}\) to a final value of \(\pi\) At the end of each increment, \(y=\cos (x)\) is calculated and displayed with the fprintf command. This process continues until \(x=\pi\).

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

Using a `while`

loop, calculate \(y=\cos (x)\) for \(-\pi \leq x \leq \pi\) using an increment of \(\frac{\pi}{4}\)

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 by adding extra formatting lines and comments:

clear; clc;

fprintf(' x cos(x)nn') % title row

fprintf(' ----------------nn') % title row

x=-pi; % initiating the x value

while x<=pi % stating the test condition

y=cos(x); % calculating the value of y

fprintf('%8.3f %8.2f nn',x,y); % printing a and y

x = x + (pi/4); % iterating to the next step

end

The result should look the same as before, but now with a header.

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

- A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m.
- Functions such as
`input`

,`disp`

and`num2str`

can be used to make scripts interactive, `fopen`

,`fprintf`

and`fclose`

functions are used to create output files,- A
`for`

loop is used to repeat a specific block of code a definite number of times. - A
`while`

loop is used to repeat a specific block of code an indefinite number of times, until a condition is met. - The
`diary`

function is useful to record a MATLAB command window session from which an m-file can be easily created, - Various style guidelines covered here help improve our code.