Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming with MATLAB

Similar presentations


Presentation on theme: "Programming with MATLAB"— Presentation transcript:

1 Programming with MATLAB
Chapter 3 Programming with MATLAB

2 Numerical Solution Newton’s Second Law Euler’s method
To obtain good accuracy, it is necessary to use many small steps Extremely laborious and time-consuming to implement by hand

3 M-Files: Scripts and Functions
You can create and save code in text files using MATLAB Editor/Debugger or other text editors (called m-files since the ending must be .m) M-file is an ASCII text file similar to FORTRAN or C source codes ( computer programs) A script can be executed by typing the file name, or using the “run” command Difference between scripts and functions Scripts share variables with the main workspace Functions do not

4 Script Files Script file – a series of MATLAB commands saved on a file, can be executed by typing the file name in the Command Window invoking the menu selections in the Edit Window: Debug, Run Create a script file using menu selection: File, New, M-file

5 Script File – Bungee Jumper
Compute the velocity of a free-falling bungee jumper at a specific time Open the editor with: File, New, M-file Save the file as bungee_jumper.m Type bungee_jumper in command window g = 9.81; m = 68.1 ; t = 20; cd = 0.25; v = sqrt(g*m/cd) * tanh(sqrt(g*cd/m)*t) » bungee_jumper v = Type the name of the script file

6 Function File Function file: M-file that starts with the word function
Function can accept input arguments and return outputs Analogous to user-defined functions in programming languages such as Fortran, C, … Save the function file as function_name.m User help function in command window for additional information

7 Functions Examples: function y = my_func (x)
One output variable function y = function_name(input arguments) More than one output variables function [y, z] = function_name(input arguments) Examples: function y = my_func (x) y = x^3 + 3*x^2 -5 * x +2 ; function area = integral (f, a, b) ya = feval (f, a); yb = feval(f, b); area = (b-a)*(ya+yb)/2;

8 Approximate the integral of f(x) = 1/x3 using basic trapezoid rule
a b Filename: trap_ex.m function t = trap_ex(a, b) t = (b - a) * (a^(-3) + b^(-3)) / 2; » y = trap_ex (1, 3) y = 1.0370

9 Script File for Integral
f(x) area x a b 1. Save integral (f, a, b) in script file integral.m 2. Save function my_func(x) in script my_func.m 3. Run script file >> area = integral(‘my_func’, 1, 10) >> area = integral(‘my_func’, 3, 6)

10 feval - evaluate function specified by string
function y = my_func(x) % function 1/x^3 y = x.^(-3); my_func.m function q = basic_trap(f, a, b) % basic trapezoid rule ya = feval(f, a); yb = feval(f, b); q = (b - a)* (ya + yb)/2; basic_trap.m » y = basic_trap ('my_func', 1,3) y = 1.0370

11 Composite Trapezoid Rule
Filename: comp_trap.m function I = Trap(f, a, b, n) % find the integral of f using % composite trapezoid rule h=(b - a)/n; S = feval(f, a); for i = 1 : n-1 x(i) = a + h*i; S = S + 2*feval(f, x(i)); end S = S + feval(f, b); I =h*S/2; f x a b

12 Composite Trapezoid Rule
one segment two segments four segments eight segments 16 segments 100 segments 500 segments 1000 segments » I=comp_trap('my_func',1,3,1) I = 1.0370 » I=comp_trap('my_func',1,3,2) 0.6435 » I=comp_trap('my_func',1,3,4) 0.5019 » I=comp_trap('my_func',1,3,8) 0.4596 » I=comp_trap('my_func',1,3,16) 0.4483 » I=comp_trap('my_func',1,3,100) 0.4445 » I=comp_trap('my_func',1,3,500) 0.4444 » I=comp_trap('my_func',1,3,1000)

13 Function File – Bungee Jumper
Create a function file freefallvel.m function velocity = freefallvel(m,cd,t) % freefallvel(m,cd,t) computes the free-fall velocity (m/s) % of an object with second-order drag % input: % m = mass (kg) % cd = second-order drag coefficient (kg/m) % t = time (sec) % output: % velocity = downward velocity (m/s) g = 9.81; % acceleration of gravity velocity = sqrt(g*m/cd) * tanh(sqrt(g*cd/m)*t);

14 Function File – Bungee Jumper
Run freefallvel.m Input: mass (m), drag coef. (cd), and time (t) >> vel1 = freefallvel(100,0.25,8) vel1 = >> vel2 = freefallvel(100,0.25,20) vel2 = >> vel3 = freefallvel(70,0.25,20) vel3 =

15 Function File To invoke the help comments Type help freefallvel
freefallvel(m,cd,t) computes the free-fall velocity (m/s) of an object with second-order drag input: m = mass (kg) cd = second-order drag coefficient (kg/m) t = time (sec) output: velocity = downward velocity (m/s)

16 Function M-Files Function M-file can return more than one result
Example – mean and standard deviation of a vector Textbook refers function M-files as simply M-files function [mean, stdev] = stats(x) % calculate the mean and standard deviation of a vector x n = length(x); mean = sum(x)/n; stdev = sqrt(sum((x-mean).^2/(n-1))); >> x=[ ]; >> [m,s] = stats(x) m = 3.6800 s = 1.7662

17 Data Files MAT Files ASCII files -- memory efficient binary format
-- preferable for internal use by MATLAB program ASCII files -- in ASCII characters -- useful if the data is to be shared (imported or exported to other programs)

18 MATLAB Input To read files in
if the file is an ascii table, use “load” if the file is ascii but not a table, file I/O needs “fopen” and “fclose” Reading in data from file using fopen depends on type of data (binary or text) Default data type is “binary”

19 Save Files 8-digit text format (variable list)
save <fname> <vlist> - ascii 16-digit text format save <fname> <vlist> - double Delimit elements with tabs save <fname> <vlist> - double - tabs Example: Vel = [1 3 5; ] save velocity.dat Vel -ascii e e e+000 e e e+000

20 Load Files Read velocity into a matrix “velocity.dat”
>> load velocity.dat >> velocity velocity = e e e+000 e e e+000

21 Note: temperature is a 62 matrix
Load Files Create an ASCII file temperature.dat read “Time” and “Temperature” from temp.dat >> load temperature.dat >> temperature % Time Temperature Note: temperature is a 62 matrix

22 MATLAB Output Matlab automatically prints the results of any calculation (unless suppressed by semicolon ;) Use “disp” to print out text to screen disp (x.*y) disp (´Temperature =´) sprintf - display combination Make a string to print to the screen output = sprintf(‘Pi is equal to %f ’, pi)

23 Formatted Output fprintf (format-string, var, ….)
%[flags] [width] [.precision] type Examples of “type” fields %d display in integer format %e display in lowercase exponential notation %E display in uppercase exponential notation %f display in fixed point or decimal notation %g display using %e or %f, depending on which is shorter %% display “%”

24 Numeric Display Format
x = [ ]; format + x = [+  ] (+/ sign only)

25 fprintf( ) of Scalar temp = 98.6;
fprintf(‘The temperature is %8.1f degrees F.\n’, temp); The temperature is degrees F. fprintf(‘The temperature is %08.2f degrees F.\n’, temp); The temperature is degrees F. fprintf(‘The temperature is %8.3e degrees F.\n’, temp); The temperature is e+001 degrees F.

26 fprintf( ) of Matrices Score = [1 2 3 4; 75 88 102 93; 99 84 95 105]
fprintf(‘Game %1.0f score: Houston: %3.0f Dallas: %3.0f \n’,Score) Game 1 score: Houston: Dallas: 99 Game 2 score: Houston: Dallas: 84 Game 3 score: Houston: Dallas: 95 Game 4 score: Houston: Dallas: 105 fprintf control codes \n Start new line \t Tab

27 Interactive input Function
The input function allows you to prompt the user for values directly from the command window Enter either “value” or “stream” n = input(‘promptstring’) function [name, sid, phone, ] = register name = input('Enter your name: ','s'); sid = input('Enter your student ID: '); phone = input('Enter your Telphone number: ','s'); = input('Enter your address: ','s'); value string

28 Interactive input Function
>> [name,sid,phone, ] = register Enter your name: John Doe Enter your student ID: Enter your Telphone number: Enter your address: name = John Doe sid = phone = =

29 Interactive M-File An interactive M-file for free-falling bungee jumper Use input and disp functions for input/output function velocity = freefallinteract % freefallinteract() % compute the free-fall velocity of a bungee jumper % input: interactive from command window % output: ve;ocity = downward velocity (m/s) g=9.81; % acceleration of gravity m = input('Mass (kg): '); cd = input('Drag coefficient (kg/m): '); t = input('Time (s): '); disp(' ') disp('Velocity (m/s):') vel = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t); disp([t;vel]’)

30 Interactive M-File >> freefallinteract Mass (kg): 68.1
Drag coefficient (kg/m): 0.25 Time (s): 0:1:20 Velocity (m/s):

31 CVEN 302-501 Homework No. 2 Chapter 3 Problems 3.1 (25), 3.4 (25)
Due Wed. 09/10/2008 at the beginning of the period

32 Common Program Structures
Sequence Selection Repetition

33 Structured Programming
Modular Design Subroutines (function M-files) called by a main program Top-Down Design a systematic development process that begins with the most general statement of a program’s objective and then successively divides it into more detailed segments Structured Programming deals with how the actual code is developed so that it is easy to understand, correct, and modify

34 The hierarchy of flowcharts dealing with a student’s GPA
Modular design Top-down design Structural Programming

35 Structured Programming
The ideal style of programming is Structured or Modular programming Break down a large goal into smaller tasks Develop a module for each task A module has a single entrance and exit Modules can be used repeatedly A subroutine (function M-file) may contain several modules Subroutines (Function M-files) called by a main program

36 Algorithm Design The sequence of logical steps required to perform a specific task (solve a problem) Each step must be deterministic The process must always end after a finite number of steps An algorithm cannot be open-ended The algorithm must be general enough to deal with any contingency

37 Structured Programming
Sequential paths Sequence – all instructions (statements) are executed sequentially from top to bottom * A strict sequence is highly limiting Non-sequential paths Decisions (Selection) – if, else, elseif Loops (Repetition) – for, while, break

38 Selection (IF) Statements
The most common form of selection structure is simple if statement The if statement will have a condition associated with it The condition is typically a logical expression that must be evaluated as either “true” or “false” The outcome of the evaluation will determine the next step performed

39 Logical IF Statements If (condition) executable_statements end
if (x < = -1.0 | x > = 1.0) y = 0. end if (x > -1.0 & x < 0.) y = 1. + x if (x > = 0. & x < 1.0) y = 1.- x y 1 x -1 1

40 Relation Operators MATLAB Interpretation == ~= < <= > >= &
| ~ Interpretation is equal to is not equal to is less than is less than or equal to is greater than is greater than or equal to and, true if both are true or, true if either one is true not

41 Logical Conditions ~ (not) – logical negation of an expression
If the expression is true, the result is false. Conversely, if the expression is false, the result is true. & (and) – logical conjunction on two expressions expression1 & expression2 If both expressions are true, the result is true. If either or both expressions are false, the result is false. | (or) – logical disjunction on two expressions expression1 | expression2 If either or both expressions are true, the result is true

42 Logical Operators 0 - 1 matrix 0: false ; 1: True

43 True Table for Logical Operators
Order of priority of logical operators Highest Lowest x y ~x x&y x|y T T F T T T F F F T F T T F F F F T F F

44 Example of a Complex Decision
If a=-1, b=2, x=1, and y=‘b’, evaluate A * b > 0 & b == 2 & x > 7 | ~(y > ‘d’) Expression 1: A*b = -2 > 0 (false) Expression 2: b = 2 (true) Expression 3: x = 1 > 7 (false) Expression 4: ‘b’ > ‘d’ (false) Expression 5: ~(Expression 4) (true) Expression 6: (Expression 1) & (Expression 2) (false) Expression 7: (Expression 6) & (Expression 3) (false) Expression 8: (Expression 7) | (Expression 5) (true)

45 Complex Decision A step-by-step evaluation of a complex decision

46 Nested IF Statement if (condition) statement block elseif (condition)
Structures can be nested within each other if (condition) statement block elseif (condition) another statement block else end

47 How to use Nested IF If the condition is true the statements following the statement block are executed. If the condition is not true, then the control is transferred to the next else, elseif, or end statement at the same if level.

48 Else and Elseif if temperature > 100
disp(‘Too hot - equipment malfunctioning.’) elseif temperature > 75 disp(‘Normal operating range.’) elseif temperature > 60 disp(‘Temperature below desired operating range.’) else disp(‘Too Cold - turn off equipment.’) end

49 Nested IF Statements nested if (if, if else, if elseif)
if (x < = -1.0) y = 0. elseif (x < = 0.) y = 1. + x elseif (x < = 1.0) y = 1. - x else y=0. end y 1 x -1 1

50 M-file: Evaluate CVEN 302 Grade
function cven302_grade name = input('Enter Student Name: ','s'); sid = input('Enter Student ID: '); HW = input('Enter Homework Average (30%): '); Exam1 = input('Enter Exam I score (20%): '); Exam2 = input('Enter Exam II score (20%): '); Final = input('Enter Final Exam score (30%): '); Average= HW*0.3 + Exam1*0.2 + Exam2*0.2 + Final*0.3; fprintf('Your Semester Average is: %6.2f \n',Average) if Average >= 90 Grade = 'A'; elseif Average >= 80 Grade = 'B'; elseif Average >= 70 Grade = 'C'; elseif Average >= 60 Grade = 'D'; else Grade = 'F'; end fprintf('Your Semester Grade is : '), disp(Grade)

51 Decisions (Selections) if … elseif Structure
>> cven302_grade Enter Student Name: Jane Doe Enter Student ID: Enter Homework Average (30%): 96 Enter Exam I score (20%): 88 Enter Exam II score (20%): 92 Enter Final Exam score (30%): 85 Your Semester Average is: Your Semester Grade is : A >> cven302_grade Enter Student Name: John Doe Enter Student ID: Enter Homework Average (30%): 62 Enter Exam I score (20%): 84 Enter Exam II score (20%): 80 Enter Final Exam score (30%): 91 Your Semester Average is: Your Semester Grade is : C

52 Do loops Repetition for i=1:m for j=1:n a(i,j)=(i+1)^2*sin(0.2*j*pi);
end

53 Ends after a specified number of repetitions
For Loops for index = start : step : finish statements end Ends after a specified number of repetitions for k = 1:length(d) if d(k) < 30 velocity(k) = *d(k).^2; else velocity(k) = *d(k)-0.01*d(k).^2 end

54 For Loop function A = for_loop(m,n) for i = 1:m for j = 1:n
A(i,j) = 50*exp(-0.2*i)^2*sin(0.1*j*pi); end >> A = for_loop(8,6) A =

55 For Loop M-file for computing the factorial n!
MATLAB has a built-in function factorial(n) to compute n! function fout = factor(n) % factor(n): % Computes the product of all the integers from 1 to n. x=1; for i = 1:n x = x*i; end fout = x; >> factor(12) ans = >> factor(100) ans = e+157

56 While Loops while condition statements
end Ends on the basis of a logical condition If the statement is true, the statements are executed If the statement is always true, the loop becomes an “infinite loop” The “break” statement can be used to terminate the “while” or “for” loop prematurely.

57 While Loop Compute your checking account balance function checking
% Compute balance in checking account Balance = input('Current Checking Account Balance ($) = '); Deposit = input('Monthly Deposit ($) = '); Subtract = input('Monthly Subtractions ($) = '); Month = 0; while Balance >= 0 Month = Month + 1; Balance = Balance + Deposit - Subtract; if Balance >= 0 fprintf('Month %3d Account Balance = %8.2f \n',Month,Balance) else fprintf('Month %3d Account Closed \n',Month) end

58 While Loop >> checking
Current Checking Account Balance ($) = Monthly Deposit ($) = Monthly Subtractions ($) = 1800 Month 1 Account Balance = Month 2 Account Balance = Month 3 Account Balance = Month 4 Account Balance = Month 5 Account Balance = Month 6 Account Balance = Month 7 Account Balance = Month 8 Account Balance = Month 9 Account Balance = Month 10 Account Balance = Month 11 Account Balance = Month 12 Account Closed

59 Nesting and Indentation
Example: Roots of a Quadratic Equation If a=0, b=0, no solution (or trivial sol. c=0) If a=0, b0, one real root: x=-c/b If a0, d=b2  4ac  0, two real roots If a0, d=b2  4ac <0, two complex roots

60 Nesting and Indentation
function quad = quadroots(a,b,c) % Computes real and complex roots of quadratic equation % a*x^2 + b*x + c = 0 % Output: (r1,i1,r2,i2) - real and imaginary parts of the % first and second root if a == % weird cases if b ~= % single root r1 = -c/b else % trivial solution error('Trivial or No Solution. Try again') end % quadratic formula else d = b^2 - 4*a*c; % discriminant if d >= % real roots r1 = (-b + sqrt(d)) / (2*a) r2 = (-b - sqrt(d)) / (2*a) else % complex roots r1 = -b / (2*a) r2 = r1 i1 = sqrt(abs(d)) / (2*a) i2 = -i1 end

61 Roots of Quadratic Equation
>> quad = quadroots(5,3,-4) r1 = 0.6434 r2 = >> quad = quadroots(5,3,4) i1 = 0.8426 i2 = >> quad = quadroots(0,0,5) ??? Error using ==> quadroots Trivial or No Solution. Try again (two real roots) (two complex roots) (no root)

62 Passing Functions to M-File
Use built-in “feval” and “inline” functions to perform calculations using an arbitrary function outvar = feval(‘funcname’, arg1, arg2, …) Funcname = inline(‘expression’, var1, var2, ...) >> fx=inline('exp(-x)*cos(x)^2*sin(2.*x)') fx = Inline function: fx(x) = exp(-x)*cos(x)^2*sin(2.*x) >> y = fx(2/3*pi) y = No need to store in separate M-file

63 Bungee Jumper: Euler’s Method
function [x, y] = Euler(f, tspan, y0, n) % solve y' = f(x,y) with initial condition y(a) = y0 % using n steps of Euler's method; step size h = (b-a)/n % tspan = [a, b] a = tspan(1); b = tspan(2); h = (b - a) / n; x = (a+h : h : b); y(1) = y0 + h*feval(f, a, y0); for i = 2 : n y(i) = y(i-1) + h*feval(f, x(i-1), y(i-1)); end x = [ a x ]; y = [y0 y ]; Use “feval” for function evaluation function f = bungee_f(t,v) % Solve dv/dt = f for bungee jumper velocity g = 9.81; m = 68.1; cd = 0.25; f = g - cd*v^2/m;

64 MATLAB M-File: Bungee Jumper
[t,v] = bungee_exact; hold on; % Exact Solution [t1,v1] = Euler('bungee_f',[0 20],0,10); % Euler method h1=plot(t1,v1,'g-s'); set(h1,'LineWidth',3,'MarkerSize',10); [t2,v2] = Euler('bungee_f',[0 20],0,20); %Euler method h2 = plot(t2,v2,'k:d'); set(h2,'LineWidth',3,'MarkerSize',10); [t3,v3] = Euler('bungee_f',[0 20],0,100); %Euler method h3 = plot(t3,v3,'mo'); hold off; set(h3,'LineWidth',3,'MarkerSize',5); h4 = title('Bungee Jumper'); set(h4,'FontSize',20); h5 = xlabel('Time (s)'); set(h5,'FontSize',20); h6 = ylabel('Velocity (m/s)'); set(h6,'FontSize',20); h7 = legend('Exact Solution','\Delta t = 2 s','\Delta t = 1 s‘, '\Delta t = 0.2s',0); set(h7,'FontSize',20);

65 Bungee Jumper Velocity

66 M-File: Bichromatic Waves
H.C. Chen M-File: Bichromatic Waves Filename waves.m (script file) % Plot Bi-chromatic Wave Profile a1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8; time = 0:0.1:100; wave1 = a1 * sin(c1*time); wave2 = a2 * sin(c2*time) + a1; wave3 = wave1 + wave2; plot(time,wave1,time,wave2,time,wave3) axis([ ]); xlabel ('time'); ylabel ('wave elevation'); title ('Bi-chromatic Wave Profile') text(42,-1.2, 'wave 1') text(42, 2.7, 'wave 2') text(59, 3.6, 'waves 1+2') MATLAB Review

67

68 MATLAB Subplots Filename waves2.m (script file)
% Plot Bi-chromatic Wave Profile % Display the results in three subplots clf % clear the graphics window a1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8; time = 0:0.1:100; wave1 = a1 * sin(c1*time); wave2 = a2 * sin(c2*time); wave3 = wave1 + wave2; subplot(3,1,1) % top figure plot(time,wave1,'m'); axis([ ]); ylabel('wave 1'); subplot(3,1,2) % middle figure plot(time,wave2,'g'); axis([ ]); ylabel('wave 2'); subplot(3,1,3) % bottom figure plot(time,wave3,'r'); axis([ ]); xlabel(’time'); ylabel('waves 1&2');

69

70 MATLAB Subplots subplot ( m, n, p ) -- 1 2 3 4 5 6
breaks the figure window into m by n small figures, select the p-th figure for the current plot » figure (3) » subplot (3, 2, 1) » plot (t,wv1) » subplot (3, 2, 2) » plot (t,wv2) » subplot (3, 2, 4) » plot (t, wv1+wv2) » subplot (3, 2, 6) » plot (t, wv1-wv2) 1 2 3 4 5 6

71 Subplot (m,n,p) Multiple plots
» x=0:0.1:10; y1=sin(pi*x); y2=sin(0.5*pi*x); y3=y1+y2; » z1=cos(pi*x); z2=cos(0.5*pi*x); z3=z1-z2; » subplot(3,2,1); H1=plot(x,y1,'b'); set(H1,'LineWidth',2); » subplot(3,2,2); H2=plot(x,z1,'b'); set(H2,'LineWidth',2); » subplot(3,2,3); H3=plot(x,y2,'m'); set(H3,'LineWidth',2); » subplot(3,2,4); H4=plot(x,z2,'m'); set(H4,'LineWidth',2); » subplot(3,2,5); H5=plot(x,y3,'r'); set(H5,'LineWidth',2); » subplot(3,2,6); H6=plot(x,z3,'r'); set(H6,'LineWidth',2); Subplot (m,n,p) Multiple plots

72 CVEN 302-501 Homework No. 3 Chapter 3 Problems 3.6 (35), 3.9 (35)
Due Mon 09/15/08 at the beginning of the period


Download ppt "Programming with MATLAB"

Similar presentations


Ads by Google