MATLAB Fundamentals
2.5 MATLAB Input/Output
◾ Sometimes, it is necessary to preallocate a matrix of a given size. This can be done by defining a matrix of all zeros or ones; for example:
=
0 0 0 0 0 0 0 0 0 A = zeros(3)
0 0 0 0 0 0 B = zeros(3,2)=
1 1 1 1 1 1 1 1 1 C = ones(3)=
1 1 1 1 1 1 D = ones(2,3)=
The function to generate the identity matrix (main diagonal of ones; all other elements are zero) is eye; example:
1 0 0 0 1 0 0 0 1 I = eye(3)=
2.5 MATLAB Input/Output
◾ If you wish to have your program pause to accept input from the keyboard, use the input function; for example, to enter a 2 by 3 matrix, use
Z = input('Enter values for Z in brackets \n');
then type in:
[5.1 6.3 2.5; 3.1 4.2 1.3]
Thus,
= 5.1 6.3 2.5 3.1 4.2 1.3 Z
Note that the argument to input() is a character string enclosed by single quotation marks, which will be printed to the screen. The \n (newline) tells MATLAB to move the cursor to the next line. Alternatively, \t (tab) tells MATLAB to move the cursor several spaces along the same line.
If you wish to enter text data to input, you need to enclose the text with single quotation marks. However, you can avoid this requirement by entering a second argument of 's' to input as shown in the following statement:
response = input('Plot function? (y/n):\n', 's');
In this case, the user can respond with either a y or n (without single quo-tation marks).
Examples (try typing these statements into the Command window):
z = input ('Enter a 2x3 matrix of your choosing\n') name=input('Enter name enclosed by single quote marks:')
response = input('Plot function? (y/n):\n', 's');
◾ The disp command prints just the contents of a matrix or alphanumeric information; for example (assuming that matrix X has already been entered in the Command window):
>> x = [3.6 7.1]; disp(X); disp('volt');
The following will be displayed on the screen:
3.6000 7.1000
volt
>>
◾ The fprintf command prints formatted text to the screen or to a file;
for example:
>> I = 2.2;
>> fprintf ('The current is %f amps \n', I);
The following will appear on the screen:
The current is 2.200000 amps
The %f refers to a formatted floating point number, and the default is six decimal places (although in earlier versions of MATLAB, the default for %f format was four decimal places).
fprintf uses format strings based on the C programming language [1].
Thus, you can specify the minimum number of spaces for the printed variable as well as the number of decimal places using
%8.2f
This will allow eight spaces for the variable, to two decimal places. You can also specify just the number of decimal places, for example, say three decimal places, and then let MATLAB automatically decide the number of spaces for the variable using
%.3f
However, to create neat looking tables, it is best to specify the number of spaces in the format statement that allows for several spaces between variables in adjacent columns.
Other formats are as follows:
%i or %d used for integers
%e scientific notation (e.g., 6.02e23), with default six decimal places
%g automatically use the briefest of %f or %e format
%s used for a string of characters
%c used for a single character
Unlike C, the format string in MATLAB’s fprintf must be enclosed by single quotation marks (and not double quotes).
Sometimes, the format part of the fprintf command may be too long to fit on a single line in your script. When this happens, you can use three dots (...) to tell MATLAB to continue the statement on a second line, as shown by the following example:
fprintf('resistance = %f volts = %f current = %f \n',...
R,V,I);
Three dots may be used to continue any MATLAB statement onto addi- tional lines to improve the readability of your script, as shown by the follow-ing statement:
a = (-4*pi^2*omega^2*r^2*(cos(arg1))^2/sqrt(arg2) +...
4*pi^2*omega^2*r^2*(sin(arg1))^2/sqrt(arg2)) *...
exp(j*pi*omega);
An alternative to using the three dots to extend a lengthy arithmetic state-ment onto more than one line is to break up the statement into several smaller statements and then combine them. As an example, we could break up the previous statement into three shorter statements to calculate a:
a1 = -4*pi^2*omega^2*r^2*(cos(arg1))^2/sqrt(arg2);
a2 = 4*pi^2*omega^2*r^2*(sin(arg1))^2/sqrt(arg2);
a = (a1+a2) * exp(j*pi*omega);
◾ Printing to a file: It is often useful to print the results of a MATLAB pro-gram to a file, possibly for inclusion in a report. In addition, program output that is printed to a file can subsequently be edited within the file, such as aligning or editing column headings in a table. Before you can print to a file, you need to open a file for printing with the command fopen. The syntax for fopen is
fo = fopen('filename','w')
Thus, fo is a pointer to the file named filename, and the w indi-cates writing.
To print to filename use
fprintf(fo,'format',var1,var2,...);
where the format string contains the text format for var1, var2, and so on. When you are finished with all of your print statements, you should close the file with the fclose command, as shown in the following example.
Example (write this simple program in the Script window and save it as io_example.m):
% io_example.m
% This program is a test for printing to a file.
clear; clc;
V = 120;
I = 2.2;
fo = fopen('output.txt','w');
fprintf (fo, 'V = %4i volt, I = %5.2f amp \n',V,I);
fclose(fo);
The extension on the output file should be .txt (otherwise, MATLAB will start the import wizard). The resulting output file can be opened from either the Script window or the Command window. To access the output file, click on File-Open, which brings up the screen shown in Figure 2.8. In the box labeled File name, type in *.txt. This will bring up all the files with the extension .txt. To open the file of interest, double click on the name of the output file (in this example, the file name is output.txt). In earlier versions of MATLAB, you would not be able to open the output file without including the fclose(fo) statement in the program. None the less it is still good practice to include the fclose statement after all the output statements in the program or at the end of the program itself.
◾ The fscanf command may be used to read from an existing file as follows:
A = zeros(n,m);
fi = fopen('filename.txt', 'r');
[A] = fscanf(fi, '%f', [n,m]);
where n × m is the number of elements in the data file. The ‘r’ in the fopen statement indicates that the file is for reading data into the program.
The n × m matrix is filled in column order. Thus, rows become columns, and columns become rows. To use the data in its original order, transpose the Figure 2.8 Files with extension .txt. (From MATLAB, with permission.)
read-in matrix. To transpose a matrix A in MATLAB, simply type in A'. This changes columns to rows and rows to columns.
◾ An existing data file can also be entered into a program by the load com-mand. The load command, unlike the fscanf command, leaves rows as rows and columns as columns.
For example:
load filename.txt
x = filename(:,1);
y = filename(:,2);
The input file must have the same number of rows in each column.