Numerical Methods for Civil Engineers
Lecture 2 - MATLAB 2
- Save & Load
- Input & Output
- Plotting Graph
Mongkol JIRAVACHARADET
SURANAREE INSTITUTE OF ENGINEERING
UNIVERSITY OF TECHNOLOGY SCHOOL OF CIVIL ENGINEERING
Save/Load Data to/from External Files
The save and load Commands
>> clear
>> x = 0:5; y=5*x;
>> save xyfile
>> save(‘xyfile’,’x’,’y’)
>> XY = [x’ y’];
>> save xyvals.txt XY -ascii
Loading Matrices from mat Files
>> clear
>> x = linspace(0,2*pi); y = cos(x); z = sin(x);
>> save trigvar
>> clear
>> whos
>> load trigvar
>> whos
Loading Data from Plain Text Files
>> clear
>> whos
>> XY = load(‘xyvals.txt’)
>> x = XY(:,1)
>> y = XY(:,2)
Input/Output Commands
Input Output - Screen
- File
User MATLAB
Command Description
disp (A) Displays the contents, but not the name, of the
Array A.
disp (‘text’) Displays the text string enclosed within single quotes.
fprintf Control the screen’s output display format.
x = input(‘text’) Displays the text in quotes, waits for user input from
the keyboard, and stores the value in x.
x = input(‘text’,’s’) Displays the text in quotes, waits for user input from
the keyboard, and stores the input as a string in x.
INPUT AND OUTPUT
Prompting for User Input
>> x = input(‘Enter a value for x’);
By default, the input function returns a numerical value.
To obtain a string input, a second parameter, ‘s’ , must be provided.
>> yourname = input(‘Enter your name ‘,‘s’);
function s = inputAbuse
% inputAbuse Use input messages to compute sum of 3 variables
x = input(‘Enter the first variable to be added ‘);
y = input(‘Enter the second variable to be added ‘);
z = input(‘Enter the third variable to be added ‘);
s = x+y+z;
Text Output
The disp Function
>> disp(‘My favorite color is red’)
>> Speed = 63;
>> disp(‘The vehicle’s predicted speed is:’)
>> disp(Speed)
Since disp requires only one argument, the message and variable
must be combined into a single string.
>> yourName = input(‘enter your name ‘,’s’);
>> disp([‘Your name is ‘,yourName])
Display Formats with the fprintf Command
Syntax Description
fprintf(‘format’,A,...) Displays the elements of the array A, and any
addition array arguments, according to the format
specified in the string ‘format’
‘format’ structure %[-][number1.number2]C, where
number1 specifies the minimum field width,
number2 specifies the number of digits to the
right of the decimal point, and C contains control
codes and format codes. Items in brackets are
optional. [-] specifies left justified.
fprintf(format)
fprintf(format,variables)
fprintf(fid,format,variables)
>> fprintf(‘Warning: x is negative\n’)
fprintf (Continue…)
Format Codes Description
%e Scientific format with lowercase e.
%E Scientific format with uppercase E.
%f Decimal format.
%g %e or %f, whichever is shorter.
Control Codes Description
\n Start new line.
\r Beginning of new line.
\b Backspace.
\t Tab.
“ Apostrophe.
\\ Backslash.
fprintf(format,variables)
>> name = ‘Elvis’; age = str2num(datestr(now,10)-1935;
>> fprintf(‘%s is %d years old\n’,name,age);
Elvis is 65 years old
>> fprintf(‘The speed is: %3.1f\n’,Speed)
The speed is: 63.2
>>r = [2.25:20:42.25];
2.25 14.137
>>circum = 2*pi*r;
22.25 139.8
>>y = [r;circum];
42.25 265.46
>>fprintf(‘%5.2f %11.5g\n’,y)
Low-Level Input/Output Functions
fopen open file Permission:
fid = fopen(filename, permission); ‘r’ read
‘rt’ read plain text file
...
‘w’ write
fclose(fid)
‘wt’ write plain text file
‘a’ append
fscanf read data from file ‘r+’ read & write
‘w+’ truncate or create
x = fscanf(fid, format); for read & write
x = fscanf(fid, format, size); ‘a+’ read & append
‘W’ write without
automatic flushing
fscanf print data to file ‘A’ append without
automatic flushing
fprintf(fid, format, variables);
fprintf(fid,format,variables)
>> x = ...
>> fout = fopen(‘myfile.dat’,’wt’);
>> fprintf(fout,’ k x(k)\n’);
>> for k = 1:length(x)
>> fprintf(fout,’%4d %5.2f\n’,k,x(k));
>> end
>> fclose(fout)
Creating a Plot
The plot function has different forms, depending on the input arguments.
If y is a vector, plot(y) produces a piecewise linear graph of the elements of y
versus the index of the elements of y.
If you specify two vectors as arguments, plot(x,y) produces a graph of y versus
x.
For example, these statements use the colon operator to create a vector of x values
ranging from zero to 2π, compute the sine of these values, and plot the result.
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)
Now label the axes and add a title. The characters \pi create the symbol π.
>> xlabel('x = 0:2\pi')
>> ylabel('Sine of x')
>> title('Plot of the Sine
>> Function','FontSize',12)
Multiple Data Sets in One Graph
Multiple x-y pair arguments create multiple graphs with a single call to plot.
MATLAB automatically cycles through a predefined (but user settable) list of colors to
allow discrimination among sets of data.
For example, these statements plot three related functions of x, each curve in a
separate distinguishing color.
>> y2 = sin(x-.25);
>> y3 = sin(x-.5);
>> plot(x,y,x,y2,x,y3)
The legend command provides an easy
way to identify the individual plots.
>> legend('sin(x)','sin(x-.25)','sin(x-.5)')
Specifying Line Styles and Colors
It is possible to specify color, line styles, and markers (such as plus signs or
circles) when you plot your data using the plot command.
>> plot(x,y,'color_style_marker')
color_style_marker is a string containing from one to four characters
(enclosed in single quotation marks) constructed from a color, a line style, and
a marker type:
• Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'.
These correspond to cyan, magenta, yellow, red, green, blue, white, and black.
• Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot.
Omit the linestyle for no line.
• Marker types are '+', 'o', '*', and 'x' and the filled marker types are :
's' for square, 'd' for diamond, '^' for up triangle, 'v' for down triangle,
'>' for right triangle, '<' for left triangle, 'p' for pentagram, 'h' for hexagram,
and none for no marker.
>> x1 = 0:pi/100:2*pi;
>> x2 = 0:pi/10:2*pi;
>> plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Adding Plots to an Existing Graph
The hold command enables you to add plots to an existing graph. When you type
hold on
MATLAB does not replace the existing graph when you issue another plotting
command; it adds the new data to the current graph, rescaling the axes if
necessary.
For example, these statements first create a contour plot of the peaks function, then
superimpose a pseudocolor plot of the same function.
[x,y,z] = peaks;
contour(x,y,z,20,'k')
hold on
pcolor(x,y,z)
shading interp
hold off
The hold on command causes the pcolor
plot to be combined with the contour
plot in one figure.