3 Input-Output & Plotting

To be really useful, a computer program must interact with the user. That means allowing the user to enter information and displaying results to the user, either in numerical, text, or graphical form. A later chapter will cover graphical user interface (GUI) programming; this chapter covers simple methods for numerical and text input/ouput and graphical display of data.

3.1 User Input

The simplest way to request information from the user of a MATLAB program is with the function, input(). This function displays a prompt to the command window asking the user to enter a value and waits for the user to respond. The value entered by the user is stored in a variable. The basic form of the call to the input function is

variable_name = input (prompt)

For example, this line requests and stores the user’s age:

>> user_age = input ('Please enter your age: ')
Please enter your age: 29

user_age =

29

In addition to numerical values, input can also accept text input. When the user is expected to enter a string rather than a number, a second argument, ‘s’, is included, as in this example:

 

>> user_name = input ('Please enter your name: ', 's')
Please enter your name: Brutus
user_name =
    'Brutus'
The value entered by the user is stored as a character array. If the ‘s’ argument is omitted, the input function expects a numerical input. If the user enters a non-numerical value, an error occurs:
>> name = input ('Please enter your name: ')
Please enter your name: Brutus
Error using input
Unrecognized function or variable 'Brutus'.Please enter your name:
This error can be circumvented by entering the response in quotes:

Please enter your name: 'Brutus'

name =

'Brutus'

but it is better to use the ‘s’ argument for the user’s convenience.

 

The user can also enter an array of values by enclosing them in brackets, as in this example:

>> quiz_scores = input ('Enter the student''s quiz scores in [ ]: ')
Enter the student's quiz scores in [ ]: [79, 83, 91, 85]

quiz_scores =

79 83 91 85

 

There is no special notation in the input function to specify that the input is an array. It simply recognizes that the response was in the form of a vector and interprets it accordingly. The user can also enter a row vector or a matrix by using the proper notation:

>> quiz_scores = input ('Enter the student''s quiz scores in [ ]: ')
Enter the student's quiz scores in [ ]: [79; 83; 91; 85]

quiz_scores =

79
83
91
85

>> user_matrix = input ('Enter a 2x2 matrix in [ ]: ')
Enter a 2x2 matrix in [ ]: [3 2; 1 4]

user_matrix =

3 2
1 4

 

Checkpoint 3.1-3.2: input

3.2 Command-line Output using disp

As discussed in Chapter 1, mixed text-numerical output can be displayed to the command window using the disp() function. The text and numerical components can be joined into a single string using +, as in this example:

>> disp("I am " + my_age + " years old")
I am 29 years old

Of course, the variable my_age must have already been defined. disp () does not have formatting capability, but the number of decimal places in a floating-point number can be controlled using the round() function:

>> BMI = 703*200/70^2

BMI =

28.6939

>> disp("My body mass index is " + round(BMI,1)) %display BMI with 1 decimal place
My body mass index is 28.7

 

Checkpoint 3.3 – 3.4: disp

3.3 Formatted Output using fprintf

The fprintf() function provides more control over the formatting of command-line output. It also allows writing to a text file (the first f stands for “file”, and the second one for “formatted”). The basic syntax of fprintf for writing to the command window is

>> fprintf('String including format descriptors and special characters', variable_list)

A format descriptor can be thought of as a placeholder; it can be interpreted as, “a value to be supplied later – in the variable list that follows.” The example above, using disp() to print “My age is…”, can be implemented with fprintf() as follows:

>> fprintf('My age is %i', my_age) 

The %i is a format descriptor that specifies an integer value. If the value being printed is a floating-point number (i.e. a number with a decimal point), the %f format descriptor is used:

>> fprintf('My body mass index is %f', BMI)

My body mass index is 28.693878

By default, the number is displayed with unreasonably high precision. To control the number of decimal places, the format descriptor is written as %.nf, where n is the desired number of digits after the decimal point. The example above, using disp() to display the body mass index with 1 decimal place, is implemented with fprintf() as follows:

>> fprintf('My body mass index is %.1f', BMI)  %display BMI with 1 decimal place
My body mass index is 28.7

Other commonly used format descriptors are %s = string, %c = character, and %e = number in scientific notation. To print the values of multiple variables intermixed with text, a format descriptor is used for each variable, and the variables are listed in the same order. For example (assuming that a variable name has already been defined):

>> fprintf('My name is %s, I am %i yrs old, and my BMI is %.1f', name, my_age, BMI)
My name is Jim, I am 29 yrs old, and my BMI is 28.7

3.3.1 Special Characters

Certain special characters, such as tab and newline, can be included in the string; often they are preceded by a backslash (\). Some of the most commonly used special characters are:

\n     newline

\t      tab

\xN    unicode, where N is the hexadecimal code of the character

\\      backslash

%%      percent symbol

It is important to remember that in a script, unlike disp(), fprintf() will not go to a new line until it encounters a \n character. Notice the difference in these two examples:

%1. newline character not included

fprintf('My name is %s', name)
fprintf('My age is %i', my_age)

My name is JimMy age is 29>>

 

%2. newline character included

fprintf('My name is %s\n', name)
fprintf('My age is %i\n', my_age)

My name is Jim
My age is 29

>>

It is best to get into the habit of always including a \n at the end of the string, except in the special cases when it is not wanted.

3.3.2 Field Width

To facilitate alignment for printing tables, the width of each number or text field can be controlled by putting the number of spaces allocated to the value immediately after the % in the format descriptor. For example, consider the difference in these two lines (03C0 is the hexadecimal unicode for [latex]\pi[/latex]):

fprintf('The value of \x03C0 is %.2f\n', pi)
fprintf('The value of \x03C0 is %8.2f\n', pi)

The value of π is 3.14
The value of π is     3.14

>>

In the first case, no field width is specified, so the minimum necessary number of spaces (4) is used to represent the number. In the second case, a field with of 8 spaces is specified, so the number is padded with 4 leading blanks.

The example below shows how these features can be used to print a right-justified table. (Note: for convenience, this example uses a for loop, which is covered in Chapter 6.)

Lecture Video 3.1 – Basic Input & Output

You can download the Live Script

 

Checkpoint 3.5: fprintf

3.4 Plotting

MATLAB has a wide range of capabilities for graphical presentation of data. This section focuses exclusively on line and scatter plots. See the MATLAB documentation or other online resources for coverage of bar charts, pie charts, contour and surface plots, etc.

The function to create a line or scatter plot is plot(). The most basic call to this function is

>> plot (x_data, y_data)

This function creates a figure window containing the plot as in this example:

>> x = -5:0.1:5;
>> y = x.^3 - 2*x.^2 + 4*x +3;
>> plot(x,y)

To annotate the plot, the functions xlabel(), ylabel(), and title() are used:

>> xlabel('x values')
>> ylabel('y values')
>> title('x^3 - 2x^2 + 4x +3')

Notice that MATLAB the ^ character as meaning exponentiation and writes the following number as a superscript.

A second data series can be added to the same plot by executing the command:

>> hold on

This tells MATLAB to overlay the next plot onto the existing one, instead of overwriting it. A plot with multiple data series should have a legend, which is added using the legend() function.

> z = -0.5*x.^4 + x.^3 - 2*x.^2 + 4*x +3;
>> hold on
>> plot(x, z)
>> legend('3rd-order', '4th-order')
>> title('Polynomials')

Notice that by default MATLAB represents each data series by a different color of solid line. The appearance of the plot – solid vs. dashed or dotted lines, line colors, markers – can be changed using control strings. For example, if the above plot is going to be printed in black-and-white, it is better to use different line styles rather than colors. This example plots both data series at once – without using hold on – one as a solid black line and the other as a dashed black line:

>> plot(x, y, 'k-', x, z, 'k--')
>> xlabel('x values')
>> ylabel('y values')
>> title('Polynomials')
>> legend('3rd-order', '4th-order', 'Location', 'Northwest')

In this example, the legend position was specified as ‘Northwest’, which means the upper-left corner. (The default is upper-right, which in this case would have covered part of the plot.) The control character for black is 'k', since 'b' is used for blue.

Another option is to represent a data series by markers instead of (or in addition to) a line. The usual practice is to use markers for experimental data and lines for theoretical curves. Suppose that there is an array of experimental results, y_exp, for a quantity that is described theoretically by the 3rd-order polynomial shown above. To plot the experimental and theoretical results on the same graph:

>> plot(x, y, 'k--', x, y_exp, 'k*')
>> xlabel('x values')
>> ylabel('y values')
>> title('Data and Theoretical Curve')
>> legend('3rd-order polynomial', 'Measured', 'Location', 'Northwest')

A list of control the characters for colors,  line styles and marker types can be found in the MATLAB documentation.

3.4.1 Sub-Plots

There are cases in which it is useful to include multiple plots in the same figure, but not on the same axes. For example, in a mechanics simulation, there may be plots of acceleration, velocity, and position, but since these quantities have different dimensions, it is not sensible to put them on the same axes.

One way of including multiple plots on separate axes in a single figure is with subplots. To include multiple plots as subplots in a single figure, the subplot() function is called prior to each plot() call. The format of the call is

>>subplot(rows, columns, index)

where rows and columns specify the arrangement of the subplots, and index specifies which subplot is currently being plotted. For example

>>subplot(3, 1, 1)

>>plot (x,y)

indicates that a 3×1 subplot – 3 plots arranged vertically – is being created, and y vs. x is plotted in the first (top) subplot.

An example of using a 3×1 subplot to graph results of a mechanics simulation is given below.

%{
Plot altitude, velocity, and acceleration from a sky-diving simulation in a 3x1 subplot. 
Since the plots share a common time axis, only use an xlabel for the bottom plot
Place a %title only on the top plot.
%}
subplot(3,1,1)
plot(t,y)
ylabel('Altitude (m)')
title ('Sky-Diving Simulation')
subplot(3,1,2)
plot(t,v)
ylabel('Velocity (m/s)')
subplot(3,1,3)
plot(t,a)
ylabel('Acceleration (m/s^2)')

xlabel('Time (s)')

A legend is not needed in this case, since each subplot has only one data series.

In the case of a 2D arrangement of subplots, the tiles are numbered row-by-row; for example, in a 2×2 subplot, the tile numbering is as follows:

1 2
3 4

Multiple tiles can be allocated for a single plot, as in the following example:

%Plot acceleration of skydiver

%First plot takes two tiles

subplot (1,3,1:2)
plot(t, a)
xlabel('Time (sec)')
ylabel ('Acceleration (m/s^2)')

title('Skydiver Simulation')

%second plot zooms in around parachute deployment

%only takes one tile
subplot(1,3,3)
plot(t, a)
xlabel('Time (sec)')
axis([50,70, -10,30])
title('Parachute Deployment')

 

3.4.2 Double-y Graphs

Another way to place multiple plots on different axes in the same graph is a double-y-axis graph. In this method, the plots share a common x-axis but use different y-axes – one on the left of the graph and one on the right. To specify which y-axis each plot uses, the command yyaxis left and yyaxis right are used.

The example below plots the altitude and velocity from the previous example on a double-y graph.

%Plot altitude and velocity on separate y-axes

yyaxis left %not really necessary, since left is the default
plot(t,y)
ylabel('Altitude (m)')

yyaxis right
plot(t,v)
ylabel('Velocity (m/s)')

xlabel('Time (s)')
title ('Sky-Diving Simulation')

 

Lecture Videos 3.2 – 3.4 – Plotting

 

Checkpoint 3.6 – 3.8: Plotting

 

3.5 Problems

 

Find an error? Have a suggestion for improvement? Please submit this survey.

 

License

MATLAB Programming for Engineering Applications Copyright © by James Toney and jayakumar5. All Rights Reserved.

Share This Book