Lecture+23 - Engineering 101 Engineering 101/27/07 MATLAB...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Engineering 101 Engineering 101 Lecture 23 11/27/07 MATLAB Programming Quote of the Day Quote of the Day Those who will not economize will have to ­ Confucius agonize. Project 7! Project 7! MATLAB Functions MATLAB Functions There are a large number of predefined mathematical functions in MATLAB. If you apply a function defined for a scalar value to a vector or matrix, the function is applied to each value. x = [ 0 0.5*pi pi 1.5*pi 2.0*pi ]; y = sin(x); % y == [ 0 1 0 –1 0 ] Trigonometric Functions Trigonometric Functions sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) atan2(y,x) sine, x in radians cosine, x in radians tangent, x in radians Arcsine in radians Arccos in radians Arctan in radians Arctan(y/x) over all quadrants Other Mathematical Functions Other Mathematical Functions abs(x) angle(x) exp(x) log(x) mod(x,y) sqrt(x) absolute value the phase angle of a complex number ex natural log of x modulo function (remainder) square root Rounding Functions Rounding Functions ceil(x) fix(x) floor(x) round(x) Ceiling (rounds up) Rounds toward zero Rounds down Rounds to nearest integer String Conversions String Conversions char(x) double(x) int2str(x) num2str(x) str2num(s) Converts numbers to characters using ASCII Converts characters to numbers Converts an integer number into a character string Converts a real number into a character string with a decimal Converts a string into a number Plotting Data in MATLAB Plotting Data in MATLAB To plot data use the function plot(x, y) x is a vector of x values y is a vector of y values x = 1:0.1:10; y = x .^ 2 – 10 .* x + 15; plot(x, y); Plotting Data in MATLAB Plotting Data in MATLAB To add a title to a graph use the function title( ) To add x and y axis labels use the functions xlabel( ) and ylabel( ) To add a grid to the graph use the grid function title(‘A Parabola); xlabel(‘x – value’); ylabel(‘y – value’); grid on; Plotting Data in MATLAB Plotting Data in MATLAB You can print your graph by using the menus or by typing print To output your graph to a TIFF file you can use the command print –dtiff filename Plotting Data in MATLAB Plotting Data in MATLAB Multiple data sets can be plotted on the same graph x = 0:0.1:10; y1 = x .^2 – 10 .* x + 15; y2 = ­ x.^2 + 10 .* x; plot(x, y1, x, y2); Plotting Data in MATLAB Plotting Data in MATLAB To distinguish between the two plots you can enter codes to set the line color, style, and marker style. color marker style line style y = yellow m = magenta c = cyan r = red g = green b = blue w = white k = black . = point o = circle x = x­mark + = plus s = square d = diamond * = star p = pentagram h = hexagram v = triangle down ^ = triangle up > = triangle right < = triangle left ­ = solid : = dotted ­. = dash­dot ­­ = dashed Plotting Data in MATLAB Plotting Data in MATLAB Multiple data sets can be plotted on the same graph Here one will be red and dot­dashed, and the other will be blue and marked with circles A legend is created with the legend function x = 0:0.1:10; y1 = x .^2 – 10 .* x + 15; y2 = ­ x.^2 + 10 .* x; plot(x, y1, ‘r_.’, x, y2, ‘bo’); legend(‘parabola up’, ‘parabola down’); Plotting Data in MATLAB Plotting Data in MATLAB In addition to linear scales data can be plotted on logarithmic and semi­logarithmic axes. plot( ) both x and y are linear semilogx( ) x is logarithmic, y islinear semilogy( ) x is linear, y is logarithmic loglog( ) both x and y are logarithmic Exercise Exercise Convert from MATLAB function to C++ procedure function [x, y] = splitstring(a) s = floor(length(a)/2) ; x = a(1 :s) ; y = a(s+1:length(a)); 1 2 3 Exercise Exercise Convert from MATLAB function to C++ procedure function [x, y] = splitstring(a) s = floor(length(a)/2) ; x = a(1 :s) ; y = a(s+1:length(a)); 1 2 3 Suppose we want to write a program in MATLAB that prompts the user for the initial height and velocity of a ball at time zero and a duration. The program then plots the height and velocity of the ball over the duration. v = g * t + v0 h = g * t2/2 + v0 * t + h0 Writing and Debugging Writing and Debugging Programs in MATLAB It is important to start by commenting your program Writing and Debugging Writing and Debugging Programs in MATLAB % gravity.m % This file computes the % trajectory of a ball % It is important to start by commenting your program The comments should include a glossary of your identifiers Writing and Debugging Writing and Debugging Programs in MATLAB % gravity.m % This file computes the % trajectory of a ball % % g = gravitational accel % x = positions of ball % x0 = initial position % v = velocities of ball % v0 = initial velocity % t = time % tmax = duration Comment individual segments of code Writing and Debugging Writing and Debugging Programs in MATLAB % gravity.m % This file computes the % trajectory of a ball % % g = gravitational accel % x = positions of ball % x0 = initial position % v = velocities of ball % v0 = initial velocity % t = time % tmax = duration % set the gravitational accel g = -9.8; Comment individual segments of code Get input from the user Writing and Debugging Writing and Debugging Programs in MATLAB % v0 = initial velocity % t = time % tmax = duration % set the gravitational accel g = -9.8; % get input from user x0 = input(‘Initial height:’); v0 = input(‘Initial velocity:’); tmax = input(‘Duration:’); Comment individual segments of code Get input from the user Make time array Writing and Debugging Writing and Debugging Programs in MATLAB % v0 = initial velocity % t = time % tmax = duration % set the gravitational accel g = -9.8; % get input from user x0 = input(‘Initial height:’); v0 = input(‘Initial velocity:’); tmax = input(‘Duration:’); % set up time t = 0:tmax/100:tmax; Comment individual segments of code Get input from the user Make time array Calculate velocity and position Writing and Debugging Writing and Debugging Programs in MATLAB % get input from user x0 = input(‘Initial height:’); v0 = input(‘Initial velocity:’); tmax = input(‘Duration:’); % set up time t = 0:tmax/100:tmax; %calculate velocity v = v0 + g * t; % calculate position x = x0 – v0 .* t + 0.5.* g .* t .^ 2; Now graph the results Writing and Debugging Writing and Debugging Programs in MATLAB % set up time t = 0:tmax/100:tmax; %calculate velocity v = v0 + g * t; % calculate position x = x0 – v0 .* t + 0.5.* g .* t .^ 2; % plot position and velocity plot(t, x, ‘r-’, t, v, ‘b:’); xlabel(‘time (s) ’); ylabel(‘h(m) /v(m/s)’); legend(‘height’, ’velocity’); grid on; gravity.m If you make a typo MATLAB will try to provide information to help you debug. Writing and Debugging Writing and Debugging Programs in MATLAB % set up time t = 0:tmax/100:tmax; %calculate velocity v = v0 + g * t; % calculate position x = x0 – v0 .* t + 0.5.* g .* t .^ 2; % plot position and velocity plot(t, x, ‘r-’, t, v, ‘b:’); xlabel(‘time (s) ’); ylabel(‘h(m) /v(m/s)’); legend(‘height’, ’velocity’); grid on; Exercise Exercise What will the M­file do? 1­ plot a parabola 3­ plot two parabolas 2­ plot a circle 4­ plot a hyperbola circle.m Exercise Exercise What will the M­file do? 1­ plot a parabola 3­ plot two parabolas 2­ plot a circle 4­ plot a hyperbola Programming in MATLAB Programming in MATLAB Just as in C++ we must have at our disposal: Sequence Iteration Selection Selection in MATLAB Selection in MATLAB Three selection constructs: if switch/case try/catch To decide if a portion of code will be executed we need to determine a condition. This requires conditional operators Conditional Operators in Conditional Operators in MATLAB == ~= > >= < <= equal to not equal to greater than greater than or equal to less than less than or equal to These return 1 for true or 0 for false Conditional Operators in Conditional Operators in MATLAB == ~= > >= < <= equal to not equal to greater than greater than or equal to less than less than or equal to Be careful with the == operator. Since all numbers are doubles small rounding errors can make expressions not equal. Conditional Operators in Conditional Operators in MATLAB == ~= > >= < <= equal to not equal to greater than greater than or equal to less than less than or equal to For example, if 0 == sin (pi) returns 0 because sin(pi) returns 1.2246e­016 Conditional Operators Conditional Operators Conditional operators can be used between arrays 1 5 > 3 1 3 ­1 ­1 2 Conditional Operators Conditional Operators Conditional operators can be used between arrays 1 5 > 3 1 0 1 3 ­1 ­1 2 1 0 Conditional Operators Conditional Operators Conditional operators can be used between arrays 1 5 > 3 1 0 1 3 ­1 ­1 2 1 0 They can also be used between a scalar and an array 5 > 8 2 10 ­1 Conditional Operators Conditional Operators Conditional operators can be used between arrays 1 5 > 3 1 0 1 3 ­1 ­1 2 1 0 They can also be used between a scalar and an array 5 > 8 2 0 1 10 ­1 0 1 Logical Operators in MATLAB Logical Operators in MATLAB & | xor( ) ~ A 0 0 1 1 B 0 1 0 1 A&B 0 0 0 1 Logical AND Logical OR Logical Exclusive OR Logical NOT A|B 0 1 1 1 xor(A, B) 0 1 1 0 Other Logical Functions Other Logical Functions ischar(a) isempty(a) isinf(a) 1 if a is a character array 1 if a is an empty array 1 if the value of a is Inf (infinity) isnan(a) 1 if the value of a is NaN (not a number) isnumeric(a) 1 if a is a numeric array Exercise Exercise What is the result of ([ 1 2; 4 5] < [2 5; 1 3]) | [1 0; 0 1] ? 1- 1 0 0 2- 1 0 0 1 3- 1 1 0 1 4- 1 0 1 0 1 Exercise Exercise What is the result of ([ 1 2; 4 5] < [2 5; 1 3]) | [1 0; 0 1] ? 1- 1 0 0 2- 1 0 0 1 3- 1 1 0 1 4- 1 0 1 0 1 Exercise Exercise What is the result of (zeros(2)==eye(2))*ones(2)? 1- 0 0 0 2- 0 0 1 1 3- 1 0 0 0 4- 1 1 1 1 1 Exercise Exercise What is the result of (zeros(2)==eye(2))*ones(2)? 1- 0 0 0 2- 0 0 1 1 3- 1 0 0 0 4- 1 1 1 1 1 The If Construct in MATLAB The If Construct in MATLAB The basic form of the if construct in MATLAB is: if control_exp1 statement1 statement2 etc. elseif control_exp2 statement 3 statement 4 etc. else statement 5 statement 6 end •Every construct must have an if and an end. •The other parts are optional. •You can have multiple elseif clauses. Example of the If Construct Example of the If Construct x = input(‘Enter a number’); if x > 0 disp(‘The number is positive’); elseif x < 0 disp(‘The number is negative’); else disp(‘The number is zero’); end Nested If Constructs Nested If Constructs You can nest if constructs much as you could in C++ if ( pos(x+1, y) == 0) if lastmovex ~= ­1 x=x+1; lastmovex = 1; end elseif (pos(x­1, y) == 0) if lastmovex ~= 1; x=x­1; lastmovex = ­1; end end The Switch Construct The Switch Construct MATLAB also has a switch construct for cases in which you are choosing from a number of alternatives: switch (switch_expr) case case_expr_1 Statement 1 Statement 2 case case_expr_2 Statement 3 Statement 4 otherwise Statement 5 end •After executing the particular case the code jumps to after the end. •The otherwise part is optional. The Switch Construct The Switch Construct MATLAB also has a switch construct for cases in which you are choosing from a number of alternatives: •One case may switch (switch_expr) case case_expr_1 multiple case Statement 1 expressions. Statement 2 case {case_expr_2, case expr_3, case_expr_4} Statement 3 Statement 4 otherwise Statement 5 end have The Switch Construct The Switch Construct switch (day) case {1, 7} disp(‘Weekend’); case 2 disp(‘Monday’); case 3 disp(‘Tuesday’); case 4 disp(‘Wednesday’); case 5 disp(‘Thursday’); case 6 disp(‘Friday’); otherwise disp(‘out of range’); end The Try/Catch Construct The Try/Catch Construct There is a special construct in MATLAB for catching errors try Statement 1 Statement 2 catch Statement 3 Statement 4 end •The try block is executed. •If an error occurs it jumps to the catch block. trytest.m The Try/Catch Construct The Try/Catch Construct a = [2 5 7 10] try i = input(‘Enter a subscript’); disp([‘value at ‘ int2str( i ) ‘ = ‘ num2str(a(i))] ); catch disp( [‘out of range:’ int2str( i )] ); end Iteration in MATLAB Iteration in MATLAB There are two formal iteration constructs in MATLAB: while for But often the most efficient way to execute a loop in MATLAB is to vectorize the operation While Loops in MATLAB While Loops in MATLAB Very similar to C++: while expression statement 1 statement 2 etc. end While Loops in MATLAB While Loops in MATLAB Very similar to C++: sum = 0; x = input(‘Enter a number:’); while x>=0 sum = sum + x; x = input(‘Enter a number:’); end disp( [‘sum = ‘ num2str(sum)] ); For Loops in MATLAB For Loops in MATLAB For­loops in MATLAB are a bit different than for­ loops in C++ for index = array Statement 1 Statement 2 etc. end •index takes the value of each column in the array in turn. For Loops in MATLAB For Loops in MATLAB prod = 1; for n = 1:10 prod = prod * n; end prod = 10! For Loops in MATLAB For Loops in MATLAB prod = 1; for n = 1:2:10 prod = prod * n; end prod = 1*3*5*7*9 For Loops in MATLAB For Loops in MATLAB prod = 1; for n = [ 2 10 3 12 7 –2 ] prod = prod * n; end prod = 2*10*3*12*7*-2 For Loops in MATLAB For Loops in MATLAB The control expression in a for­loop in MATLAB can even be an array with more than one dimension. In this case the index takes on the value of an entire column one column at a time. What is the result in x after: a = [1 : 3; 2:2:6]; x = ones(2,1); for b = a x = x.*b; end Exercise Exercise 1­ [ 3 2­ [ 3 3­ [ 6 4­ [ 6 48 ] 12 ] 48 ] 12 ] What is the result in x after: a = [1 : 3; 2:2:6]; x = ones(2,1); for b = a x = x.*b; end Exercise Exercise 1­ [ 3 2­ [ 3 3­ [ 6 4­ [ 6 48 ] 12 ] 48 ] 12 ] break and continue break and continue There are two commands you can insert into a MATLAB loop to alter the flow of control. break will cause the program to immediately exit the loop continue will cause the program to skip to the end of the loop, but the loop will continue to iterate if it is not complete. break and continue break and continue for i = 1:2:11 if mod(i, 3)==0 continue; end display( i ); 1 end 5 7 11 for i = 1:2:11 if mod(i, 3) == 0 break; end display( i ); 1 end Reading a matrix from a file Reading a matrix from a file You can load data in from a file using: >> load filename.dat If the file contains only a matrix of numbers, this places the data in “filename.dat” into an array called “filename” You can then use “filename” like a normal matrix Next Lecture Next Lecture Subarrays and Vectorization ...
View Full Document

This note was uploaded on 03/12/2010 for the course ENGIN 101 taught by Professor Jeffringenberg during the Fall '07 term at University of Michigan.

Ask a homework question - tutors are online