Вы находитесь на странице: 1из 8

Numerical Methods for Civil Engineers

Lecture 2 - MATLAB 2
- Save & Load - Input & Output - Plotting Graph

Mongkol JIRAVACHARADET

SURANAREE UNIVERSITY OF TECHNOLOGY

INSTITUTE OF ENGINEERING 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 User
Command disp (A) disp (text) fprintf x = input(text)

Output

- Screen - File

MATLAB
Description Displays the contents, but not the name, of the Array A. Displays the text string enclosed within single quotes. Control the screens output display format. 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 y z s = = = = input(Enter the first variable to be added ); input(Enter the second variable to be added ); input(Enter the third variable to be added ); x+y+z;

Text Output
The disp Function
>> disp(My favorite color is red) >> Speed = 63; >> disp(The vehicles 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 Scientific format with lowercase e. Scientific format with uppercase E. Decimal format.

%e %E %f %g
Control Codes

%e or %f, whichever is shorter.


Description Start new line. Beginning of new line. Backspace. Tab. Apostrophe. Backslash.

\n \r \b \t \\

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 >>circum = 2*pi*r; 22.25 >>y = [r;circum]; 42.25 >>fprintf(%5.2f %11.5g\n,y) 265.46 139.8 14.137

Low-Level Input/Output Functions


fopen open file
fid = fopen(filename, permission); ... fclose(fid)

Permission:
r rt w wt a r+ w+ a+ W A read read plain text file write write plain text file append read & write truncate or create for read & write read & append write without automatic flushing append without automatic flushing

fscanf read data from file


x = fscanf(fid, format); x = fscanf(fid, format, size);

fscanf print data to file


fprintf(fid, format, variables);

fprintf(fid,format,variables)
>> x = ... >> fout = fopen(myfile.dat,wt); >> fprintf(fout, k x(k)\n); %5.2f\n,k,x(k)); >> for k = 1:length(x) >> fprintf(fout,%4d >> 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.

Вам также может понравиться