Professional Documents
Culture Documents
MATLAB Functions and Data Import-Export Utilities
MATLAB Functions and Data Import-Export Utilities
At this point you should be able to write a MATLAB program that inputs data,
performs simple arithmetic operations on it, perhaps involving loops and deci-
sions, and displays the results of the computation in a comprehensible form.
However, more interesting problems in science and engineering are likely to
involve special mathematical functions like sines, cosines, logarithms, and the
like. MATLAB comes with a large collection of such functions; we have seen
some of them already. This chapter introduces you to the more common func-
tions available in MATLAB. In addition, because you may wish to import data
to be plotted or operated on mathematically, and export data for future use,
the chapter also introduces you to the importing of data into the MATLAB
workspace from various sources and discusses the exporting of data to files in
your working directory.
Copyright © 2010, Daniel T. Valentine. Published by Elsevier Ltd. All rights reserved.
DOI: 10.1016/B978-0-12-374883-6.00004-7 91
92 CH A P T E R 4: MATLAB Functions and Data Import–Export Utilities
Alternatively, go to the Contents listing in the Help Navigator (the left pane
in the Help browser) and expand successively MATLAB, Reference, MATLAB
Function Reference, where you can choose either Functions by Category or
Alphabetical List of Functions.
Note that if the argument of a function is an array, the function is applied
element by element to all the values in the array. For example,
sqrt([1 2 3 4])
returns
Since this text is written in a tutorial style, it is expected that you will examine
the following list of common MATLAB functions. It is also expected that you
already know, from your first courses in mathematics and science, something
about them. One way to examine these functions is to plot them. Have some fun
experimenting with MATLAB in your investigation of the following functions.
For example, do the following exercise for all functions of the assigned variable
x, as illustrated next.
x = –1:.1:1; <Enter>
plot(x,abs(x),’o’) <Enter>
t = clock;
fprintf( ’ %02.0f:%02.0f:%02.0f\n’,
t(4), t(5), t(6) );
6
(a)
(c)
2
22
(b)
24
22 21.5 21 20.5 0 0.5 1 1.5 2
FIGURE 4.1
(a) Exponential, (b) hyperbolic sine, and (c) hyperbolic cosine functions.
94 CH A P T E R 4: MATLAB Functions and Data Import–Export Utilities
feet = fix(40/12)
inches = rem(40, 12)
Let’s next look at an example that will hopefully inspire you to examine all
of the functions listed as well as any other MATLAB function you may dis-
cover. We will consider arc-cosine, arc-sine, and arc-tangent: acos(x), acos(x),
and atan(x), respectively. If you specify x—that is, the cosine, the sine, and
the tangent, respectively, between –1 and 1—in what quadrant of the circle
are the output angles selected? To provide an answer, the following M-file
script was created and executed. The graphical comparison of the computed
results is illustrated in Figure 4.2. REMARKS at the end of the script provides
4.1 Common Functions 95
1
asin(x)
acos(x)
0.8 atan(x)
0.6
x (argument of the function)
0.4
0.2
20.2
20.4
20.6
20.8
21
2100 250 0 50 100 150 200
in (degrees)
FIGURE 4.2
Comparison of results from the acos, asin, and atan functions.
%
% Script to compare the acos(x), asin(x), and atan(x)
% functions over the range –1 < x < 1. The values are
% converted to angles in degrees. The results are
% compared graphically.
%
% Script prepared by D. T. Valentine – September 2006.
% Comments modified by D.T.V. ......... November 2008.
%
% The question raised is: What range of angles, i.e.,
% which of the four quadrants of the circle from 0 to
% 2*pi are the angular outputs of each of the functions?
%
% Assign the values of x to be examined:
%
x = –1:0.001:1;
%
% Compute the arc-functions:
%
y1 = acos(x);
96 CH A P T E R 4: MATLAB Functions and Data Import–Export Utilities
y2 = asin(x);
y3 = atan(x);
%
% Convert the angles from radians to degrees:
%
y1 = 180*y1/pi;
y2 = 180*y2/pi;
y3 = 180*y3/pi;
%
% Plot the results:
%
plot(y1,x,y2,x,y3,x),grid
legend(’asin(x)’, ’acos(x)’, ’atan(x)’)
xlabel(’\theta in degrees’)
ylabel(’x, the argument of the function’)
%
% REMARKS: Note the following:
% (1) The acos(x) varies from 0 to 90 to 180 degrees.
% (2) The asin(x) varies from –90 to 0 to 90 degrees.
% (3) The atan(x) varies from –90 to 0 to 90 degrees.
% To check remark (3) try atan(1000000)*180/pi.
%
% Stop
A =
1 2 3
4 5 6
If you view myData.txt in a text editor (or type it in the Command Window)
it looks like this:
Delimiters are the characters used to separate the data values in the file—spaces
by default. You can use tabs instead of spaces by specifying the –tabs qualifier
instead of –ascii. If you save character arrays (strings) in this way, the ASCII
codes of the characters are written to the file.
load myData.txt
creates a variable in the workspace with the same name as the file, minus the
extension: myData. If you don’t want the filename as the variable name, use the
functional form of the command:
A = load(’myData.txt’)
Data imported in this way doesn’t have to be created by MATLAB. You can create
it in a text editor in any other program that exports data in ASCII format.
save filename x y z
Note:
■ If no variables are listed, the entire workspace is saved.
■ The extension .mat is the default—you can specify a different extension.
■ Seek Help for all save options.
The command
load filename
loads all the variables from filename.mat into the workspace; see Help for all
load options.
while ˜isempty(str)
str = input( ’Enter name: ’, ’s’ );
if ˜isempty(str)
if length(str) > namelen
name = str(1:namelen); %only first ten chars allowed
else
name = str;
name(length(str)+1:namelen) = ’ ’; %pad with blanks if
...too short
end
fwrite(fid, name);
100 CH A P T E R 4: MATLAB Functions and Data Import–Export Utilities
fclose(fid);
Note that
■ The statement
fid = fopen(’marks.bin’, ’w’);
writes all the characters in name to the file (one byte each).
■ The second fwrite statement
■ The statement
fclose(fid);
closes the file (returning 0 if the operation succeeds). Although MATLAB
automatically closes all files when you exit, it is good practice to close
files explicitly with fclose when you have finished using them.
Note that you can close all files with fclose(’all’).
while ˜feof(fid)
str = fread(fid,namelen);
name = char(str’);
mark = fread(fid, 1, ’float’);
fprintf(’%s %4.0f\n’, name, mark)
end
fclose(fid);
fclose(fid);
which moves the file position indicator to byte 14 from the beginning of
the file, ready to start accessing at byte 15, which is the beginning of the
second record. The function fseek returns 0 (successful) or –1
(unsuccessful). Incidentally, if you get lost, you can always used ftell
to find out where you are!
■ The fread statement, which reads the mark to be changed,
automatically advances the file position indicator by four bytes (the
number of bytes required by float precision). In order to overwrite the
mark, we therefore have to move the file position indicator back four
bytes from its current position, The statement
fseek(fid, –4, ’cof’);
achieves this.
■ The fwrite statement then overwrites the mark.
The programs above have no error-trapping devices that, for example, prevent
you from reading from a nonexistent file or prevent you from overwriting a
record that isn’t there. It is left to you to fill in these sorts of details.
SUMMARY
CHAPTER EXERCISES
C 2 = A2 + B 2 − 2AB cos(θ).
m2 (1 + e)tan(α)
tan(β) =
m1 − em2 + (m1 + m2 )tan2 (α)
Write a script to input values of m1 , m2 , e, and α (in degrees) and to compute the angle
β in degrees.
4.5. Section 2.7 has a program for computing the members of the sequence xn = an /n. It
displays every member xn computed. Adjust it to display only every tenth value of xn .
Hint: the expression rem(n, 10) will be zero only when n is an exact multiple of 10.
Use this in an if statement to display every tenth value of xn .
4.6. To convert the variable mins, minutes, into hours and minutes, you use fix(mins/60)
to find the whole number of hours and rem(mins, 60) to find the number of minutes
left over. Write a script that inputs a number of minutes and converts it to hours and
minutes.Then write a script to convert seconds into hours, minutes, and seconds.Tryout
on 10,000 seconds, which should convert to 2 hours 46 minutes, and 40 seconds.
4.7. Design an algorithm (i.e., write the structure plan) for a machine that must give the
correct amount of change from a $100 bill for any purchase costing less than $100. The
plan must specify the number and type of all bills and coins in the change, and should
in all cases give as few bills and coins as possible. (If you are not familiar with dollars
and cents, use your own monetary system.)
4.8. A uniform beam is freely hinged at its ends, x = 0 and x = L, so that the ends are at
the same level. It carries a uniformly distributed load of W per unit length, and there is
Summary 105
a tension, T , along the x -axis. The deflection, y , of the beam a distance, x , from one end
is given by
WEI cosh[a(L/2 − x )] Wx (L − x )
y = − 1 +
T2 cosh(aL/2) 2T
where a2 = T /EI , E being the Young’s modulus of the beam and I the moment of inertia
of a cross-section of the beam. The beam is 10 m long, the tension is 1000 N, the load is
100 N/m, and EI is 104 .
Write a script to compute and plot a graph of the deflection y against x (MATLAB has
a cosh function). To make the graph look realistic you will have to override MATLAB’s
automatic axis scaling with the statement
after the plot statement, where xmin and so forth have appropriate values.