matlab.pdf

10
Lecture 3 - MATLAB 3 Numerical Methods for Numerical Methods for Civil Civil Engineers Engineers - Function m Function m- files files - Script m Script m- files files - Flow Control Flow Control Mongkol JIRAVACHARADET S U R A N A R E E INSTITUTE OF ENGINEERING UNIVERSITY OF TECHNOLOGY SCHOOL OF CIVIL ENGINEERING Programming with MATLAB : Programming with MATLAB : M-file is just a plain text file ended with extension “.m” To open the built-in editor, select menu: File > New > M-file Script Files Script Files You can perform operations in MATLAB in two ways: 1. Enter commands directly in the Command Window. 2. Run a script M-file which contains all the commands – one at a time.

description

matlab.

Transcript of matlab.pdf

Page 1: matlab.pdf

Lecture 3 - MATLAB 3

Numerical Methods for Numerical Methods for CivilCivil EngineersEngineers

-- Function mFunction m--filesfiles

-- Script mScript m--filesfiles

-- Flow ControlFlow Control

Mongkol JIRAVACHARADET

S U R A N A R E E INSTITUTE OF ENGINEERINGUNIVERSITY OF TECHNOLOGY SCHOOL OF CIVIL ENGINEERING

Programming with MATLAB :Programming with MATLAB :

M-file is just a plain text file ended with extension “.m”

To open the built-in editor, select menu: File > New > M-file

Script FilesScript FilesYou can perform operations in MATLAB in two ways:

1. Enter commands directly in the Command Window.2. Run a script M-file which contains all the commands – one at a time.

Page 2: matlab.pdf

A Script to Plot FunctionsA Script to Plot Functions

trigplot.mt = linspace(0,2*pi);y1 = sin(t);y2 = cos(t);y3 = y1.*y2;plot(t,y1,’-’,t,y2,’.’,t,y3,’—’);

>> trigplotReplace the plot statement with

plot(t,y1,’-’,t,y2,’:’,t,y3,’—’);axis([0 2*pi -1.5 1.5])legend(‘sin(t)’,’cos(t)’,’sin(t)*cos(t)’);

>> close all; trigplot

Page 3: matlab.pdf

Use TEX notation to display “θ”

legend(‘sin(\theta)’,’cos(\theta)’,’sin(\theta)*cos(\theta)’);

xlabel(‘\theta (radius)’,’FontName’,’Times’,’FontSize’,14)

>> close all; trigplot

>> x = linspace(0,2*pi);>> y1 = sin(x);>> y2 = cos(x);>> y3 = y1.*y2;>> plot(x,y1,'-',x,y2,':',x,y3,'--');>> axis([0 2*pi -1.5 1.5])>> legend('sin(\theta)','cos(\theta)','sin(\theta)*cos(\theta)')>> xlabel('\theta (radius)','FontName','Times','FontSize',14)>> title('Plot of simple trigonometric functions',...

'FontName','Times','FontSize',12)

Page 4: matlab.pdf

FunctionFunction mm--FilesFiles

pyt.mfunction h = pyt(a, b)% PYT hypotenuse of a right-angled triangleh = sqrt(a.^2 + b.^2);

>> pyt(3,4)

Command Window>>

input parameters

function

output parameters

function [outputParameterList] = functionName(inputPramaterList)

Input argument

function name

output argument

average.m is a simple function that calculates the average of the elements in a vector.

function y = average(x)% AVERAGE Mean of vector elements.% AVERAGE(X), where X is a vector, is the mean of vector elements.y = sum(x)/length(x); % Actual computation>> z = 1:99;>> average(z)

ans =50

The H1 Line is the first help text line.>> lookfor average

Help Text : >> help average

AVERAGE Mean of vector elements.

AVERAGE Mean of vector elements.AVERAGE(X), where X is a vector, is the mean of vector elements.

Page 5: matlab.pdf

Creating PCreating P--Code Code FilesFiles

You can convert average.m into a pseudocode called P-code file.

>> pcode average

Text file:can be viewedby any editor

Pseudocode:can’t be viewedby any editor

- Faster for large program

- Use to hide algorithm

FLOW CONTROLFLOW CONTROL

MATLAB has several flow control constructs:

•• ifif•• switch & caseswitch & case•• forfor•• whilewhile•• continuecontinue•• breakbreak

Page 6: matlab.pdf

if Conditional Control

if condition

expression

elseif condition

expression

elseexpression

end

Condition:Equal A == B

Not equal A ~= B

Greater A > BSmaller A < B

Greater or equal A >= B

Smaller or equal A <= B

AND &

OR |

The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements.

if a < 0disp(‘a is negative’);

end

Example 1:

if a < 0, disp(‘a is negative’); endExample 2:

if x >= yc = x^2 - y;

elseif y/x > 2.0c = log(y/x);

elsec = x + y;

end

Example 3:

Page 7: matlab.pdf

switch expressioncase value1

block of statementscase value2

block of statements...

otherwiseblock of statements

end

switch sign(x)case -1disp(‘x is negative’);

case 0disp(‘x is exactly zero’);

case 1disp(‘x is positive’);

otherwisedisp(‘sign test fail’);

end

switch & caseThe switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch.

>> P = zeros(5, 5);

>> for k = 1:5for l = 1:5

P(k, l) = pyt(k, l);end

end

>> P

forThe for loop repeats a group of statements a fixed, predetermined number of times.

A matching end delineates the statements.

Page 8: matlab.pdf

while condition

expressions

end

Break Loops break

>> x=1;>> while 1+x > 1

x = x/2;end

>> x

Return Loops return

returnbreak

LOOP

whileThe while loop repeats a group of statements an indefinite number of times under control of a logical condition.

A matching end delineates the statements.

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial.

a = 0; fa = -Inf;b = 3; fb = Inf;while b-a > eps*b

x = (a+b)/2;fx = x^3-2*x-5;if sign(fx) == sign(fa)

a = x; fa = fx;else

b = x; fb = fx;end

endx

The result is a root of the polynomial x3 - 2x - 5, namely

x =2.09455148154233

a

fa

fb

bx

Page 9: matlab.pdf

To open a new figure window and make it the current figure, type

Figure WindowsFigure Windows

Graphing functions automatically open a new figure window if there are nofigure windows already on the screen. If a figure window exists, MATLAB usesthat window for graphics output. If there are multiple figure windows open,

MATLAB targets the one that is designated the “current figure” (the last figure used or clicked in).

To make an existing figure window the current figure, you can click the mouse while the pointer is in that window or you can type

figure(n)where n is the number in the figure title bar. The results of subsequent graphics commands are displayed in this window.

figure

Multiple Plots in One FigureMultiple Plots in One Figure

>> t = 0:pi/10:2*pi;>> [X,Y,Z] = cylinder(4*cos(t));>> subplot(2,2,1); mesh(X)>> subplot(2,2,2); mesh(Y)>> subplot(2,2,3); mesh(Z)>> subplot(2,2,4); mesh(X,Y,Z)

The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing

subplot(m,n,p)partitions the figure window into an m-by-n matrix of small subplots and selectsthe pth subplot for the current plot.The plots are numbered along first the top row of the figure window, then the second row, and so on.For example, these statements plot data in four different subregions of the figure window.

Page 10: matlab.pdf

3-D PlotFirst, create 1D vectors describing the grids in the x- and y-directions:>> x = (0:2*pi/20:2*pi)';>> y = (0:4*pi/40:4*pi)';Next, ``spread'' these grids into two dimensions using meshgrid:>> [X,Y] = meshgrid(x,y);>> whosEvaluate a function z = f(x,y) of two variables on the rectangular grid:>> z = cos(X).*cos(2*Y);

Plotting commands:

>> mesh(x,y,z)>> surf(x,y,z)>> contour(x,y,z)