Professional Documents
Culture Documents
Lecture 3 - MATLAB 3
Programming with MATLAB :
- Script m-files - Function m-files - Flow Control
Mongkol JIRAVACHARADET
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. M-file is just a plain text file ended with extension .m To open the built-in editor, select menu: File > New > M-file
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)
Function m-Files
Command Window >> input parameters function output parameters function [outputParameterList] = functionName(inputPramaterList)
output argument function name
Input argument
% PYT hypotenuse of a right-angled triangle h = sqrt(a.^2 + b.^2); >> pyt(3,4) 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
Pseudocode: cant be viewed by any editor - Faster for large program - Use to hide algorithm
FLOW CONTROL
MATLAB has several flow control constructs:
if Conditional Control
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 condition expression elseif condition expression else expression end
Condition:
Equal Not equal Greater Smaller Greater or equal Smaller or equal AND OR A == B A ~= B A>B A<B A >= B A <= B & |
Example 1: if a < 0 disp(a is negative); end Example 2: if a < 0, disp(a is negative); end Example 3: if x >= y c = x^2 - y; elseif y/x > 2.0 c = log(y/x); else c = x + y; end
case value2
block of statements
. . . otherwise
block of statements
switch sign(x) case -1 disp(x is case 0 disp(x is case 1 disp(x is otherwise disp(sign end
end
for
The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. >> P = zeros(5, 5); >> for k = 1:5 for l = 1:5 P(k, l) = pyt(k, l); end end >> P
while
The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.
Break Loops
break
return
Return Loops
return
break
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 end x
fb
fa
Figure Windows
Graphing functions automatically open a new figure window if there are no figure windows already on the screen. If a figure window exists, MATLAB uses that 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. To open a new figure window and make it the current figure, type
figure
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects the 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. >> >> >> >> >> >> 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)
3-D Plot
First, 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); >> whos Evaluate 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)