Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Matlab for Engineering Applications Introduced by Jen-Yang Chen Department of Electronic Engineering Ming Chuan University.

Similar presentations


Presentation on theme: "1 Matlab for Engineering Applications Introduced by Jen-Yang Chen Department of Electronic Engineering Ming Chuan University."— Presentation transcript:

1 1 Matlab for Engineering Applications Introduced by Jen-Yang Chen Department of Electronic Engineering Ming Chuan University

2 2 Introduction Matlab: Matrix Laboratory Matlab is both a computer programming language and a software environment for using language effectively. Matlab has a number of add-on software modules, called toolboxes, that perform more specialized computations, dealing with applications such as –Image and signal processing –Financial analysis –Control systems design –Communication systems –Fuzzy logic –Neural networks –Filter design –Optimization –Partial differential equations –Statistics –System identification –Virtual reality –Wavelet –…

3 3 Contents Matlab Windows and Menus Basic Operations and Arrays Files, Functions Plotting with Matlab Programming with Matlab Numerical Methods for Differential Equations

4 4 1. Matlab Windows and Menus

5 5 Enter commands and expressions at the prompt position (>>) in command window. Ex: r = 8/10

6 6 1. Matlab Windows and Menus u = [0:.1:10]  u = 0,0.1,0.2,0.3,…,9.8,9.9,10 z = 5*sin(u)  z = 5sin(0), 5sin(0.1), …5sin(9.9), 5sin(10).

7 7 1. Matlab Windows and Menus We can create a new program file, called M-file, using a text editor.

8 8 1. Matlab Windows and Menus

9 9 2. Basic Operations and Arrays Row vector >> r = [2,4,10]; >> n = [2,4,10] n = 2 4 10 >> n = [2 4 10] n = 2 4 10 Column vector >> r = [2; 4;10] r = 2 4 10 >> y = [ 2 4 10]’ y =2 4 10 Ex: r =[ 2 4 10] >> v = 5*r v = [10 20 50] >>w = r + v w = [12 24 60] >> u = [r, w] u = [2 4 10 12 24 60] Ex: Creat a row vector from 5 to 30, incremented by 0.1. >> t = [5:0.1:30] t = 5, 5.1,5.2,…, 29.8,29.9,30.

10 10 2. Basic Operations and Arrays Matrix >> a = [2,4,10;16,3,7] a = 2 4 10 16 3 7 Ex: A = [6, -2;10,3;4,7], B = [9,8;-5,12] >> A*B ans 6424 75116 1 116 Array operations Ex: a =[1:5]; b = [3:7]; >> a = [1:5] a = 12345 >> b = [3:7] b = 34567 >> c = a.* b c = 38152435 >> c = a./ b c = 0.333 0.5 0.6 0.6670.7143 >> c = a.^ b c = 116 243409678125

11 11 2. Basic Operations and Arrays Ex: >> x = [0:0.01:1]; >> y = exp(-x).* sin(x)./sqrt(x.^2 +1); >>plot(x,y)

12 12 3. Files and Functions Matlab uses two types of M-files: script files and function files. A script file contains a sequence of Matlab commands and is useful when you need to use many commands or arrays with many elements. A function file is useful when you need to repeat a set of commands several times.

13 13 3. Files and Functions Example of a simple script file computes the matrix C=AB and displays it on the screen. % Program ‘prod_abc.m’ %This program computes the %matrix product C = A * B,and %displays the result. A=[1,4;2,5]; B=[3,6;1,2]; C=A*B In the Matlab command window type the script file’s name prod_abc to execute the program. >>prod_abc C= 7 14 11 22

14 14 3. Files and Functions Function file: All the variables in a function file are local, which means their values are available only within the function. Function files are useful when you need to repeat a set of commands several times. Function files are like functions in C, subroutines in BASIC, and procedures in Pascal. Its syntax is as follows: function [output variables] = function_name(input variables); Note: (i) output variables are enclosed in square brackets, the square brackets are optional when there is only one output. (ii) input variables are enclosed with parentheses (iii) function_name must be the same as the filename in which it is saved (with the.m extension) (iv) function is called by its name.

15 15 3. Files and Functions Ex:, find the value of x that gives a minimum of y for. function y=f2(x) y=1-x.* exp (-x); Save it as f2.m In command window, type x=fmin(‘f2’, 0, 5). The answer is x = 1. To find the minimum value of y, type y = f2(x).

16 16 3. Files and Functions

17 17 4. Plotting with Matlab XY plotting functions Ex:>>x = [0:0.1:52]; >>y = 0.4*sqrt(1.8*x); >>plot(x,y) >>xlabel(‘Distance (miles)’) >>ylabel(‘Height (miles)’) >>title(‘Tocket height as a function of downrange distance’)

18 18 4. Plotting with Matlab The function plot command fplot Syntax fplot(‘string’,[xmin xmax]) or fplot(‘string’,[xmin xmax ymin ymax]) Ex:>> f = ‘cos(tan(x))-tan(sin(x))’; >>fplot(f, [1 2])

19 19 4. Plotting with Matlab Ex: plot the hyperbolic sine and tangent x = [0:0.01:2]; y = sinh(x); z = tanh(x); plot(x,y,x,z,’- -‘), xlabel(‘x’), … ylabel(‘Hyperbolic sine and tangent’),… legend(‘sinh(x)’, ‘tanh(x)’)

20 20 4. Plotting with Matlab Data markers, line types and colors Data markers:. * x o + Line types: - -- -. : Colors: black(k) Blue(b) Green(g) Red(r) Yellow(y)

21 21 4. Plotting with Matlab Surface mesh plots (z=f(x,y)) [X,Y]=meshgrid(x,y), if x=[xmin:xspacing:xmax], y=[ymin:yspacing:ymax] The meshgrid function generates the grid point in the xy plane, and then evaluate the function f(x,y) at these points.

22 22 4. Plotting with Matlab Ex: with a spacing of 0.1. >>[X,Y]=meshgrid(-2:0.1:2); >>Z=X.*exp(-((X-Y.^2).^2+Y.^2)); >>mesh(X,Y,Z), xlabel(‘x’), ylabel(‘y’),zlabel(‘z’)

23 23 4. Plotting with Matlab Contour plots Ex: >>[X,Y]=meshgrid(-2:0.1:2); >>Z=X.*exp(-((X-Y.^2).^2+Y.^2)); >>contour(X,Y,Z), xlabel(‘x’), ylabel(‘y’)

24 24 5. Programming with Matlab Relational operators < less than <=less than or equal to > greater than >=greater than or equal to = =equal to ~=not equal to Logical operations ~ not & and |or xor(a,b)exclusive or

25 25 5. Programming with Matlab Conditional statements (1) if logical expression statements end Ex: if x >= 0 y = sqrt(x) end or it can be written on a single line if x >= 0, y = sqrt(x), end

26 26 5. Programming with Matlab (2) Nest if statements if logical expression 1 statement group 1 if logical expression 2 statement group 2 end

27 27 5. Programming with Matlab (3) The else statement if logical expression statement group 1 else statement group 2 end Ex: and that if x >= 0 y= sqrt(x) else y = exp(x) – 1 end

28 28 5. Programming with Matlab (4) The elseif statement if logical expression 1 statement group 1 elseif logical expression 2 statement group end Ex: y = lnx if x >= 5, y = sqrt(x) if 0<= x < 5 if x >= 5 y = log(x) elseif x >= 0 y = sqrt(x) end

29 29 5. Programming with Matlab Loops for loop variable = m:s:n Statements end m:s:n=>initial value m, incremented by the value s and terminated by the value n. Note: s may be negative, k=10:-2:4 produce k = 10,8,6,4. if s is omitted, the step value defaults to one.

30 30 5. Programming with Matlab Ex: implied loops x= [0:5:100]; y = cos(x); To achieve the same result using a for loop, we must type for k = 1: 21 x = (k-1) *5; y(k) = cos(x); end

31 31 5. Programming with Matlab While loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance. while logical expression statements End Ex: x = 5; while x <25 disp (x) x = 2*x-1; end The results displayed by the disp statement are 5, 9, and 17.

32 32 5. Programming with Matlab For the while loop to function properly, the following two conditions must occur; The loop variable must have a value before the while statement is executed. The loop variable must be changed somehow by the statements.

33 33 5. Programming with Matlab Switch structure: Anything programmed using switch can also be programmed using if structures. However, for some applications the switch structure is more readable than code using the if structures. switch input expression (scalar or string) case value1 statement group 1 case value2 statement group 2 … otherwise statement group n end

34 34 5. Programming with Matlab Ex: variable angle switch angle case 45 disp(‘Northeast’) case 135 disp(‘Sortheast’) case 225 disp(‘Southwest’) case 315 disp(‘Northwest’) otherwise disp(‘Direction Unknown’) end

35 35 6. Numerical Methods for Differential Equations Euler method: first order differential equation, high order differential equation In general, as the accuracy of the approximation is increased, so is the complexity of the programming involved. Understanding the concept of step size and its effects on solution accuracy is important.

36 36 6. Numerical Methods for Differential Equations Consider the equation r(t) is a known function We have, where is the step size. For convenience,

37 37 6. Numerical Methods for Differential Equations Example:, r = -10, y(0) = 2, plots the y trajectory over the range, step size, which is 20% of the time constant. True solution is, with time constant

38 38 6. Numerical Methods for Differential Equations eulermethod.m r = -10; delta = 0.02; y(1) = 2; k = 0; for time = [delta:delta:0.5] k = k+1; y(k+1) = y(k)+r*y(k)*delta; end t = [0:delta:0.5]; y_true = 2 * exp(-10*t); plot(t,y,’o’,t,y_true);

39 39 6. Numerical Methods for Differential Equations

40 40 6. Numerical Methods for Differential Equations There is some noticeable error from the result of above figure. If we use a step size equal to 5% of the time constant, the error would not be noticeable on the following plot. However, the smaller step size requires longer run times.

41 41 6. Numerical Methods for Differential Equations Matlab ODE Solvers ode23 and ode45 can be used to solve differential equations. Basic syntax for solvers: [t,y]=ode23(‘ydot’,tspan,y0) where ydot is the name of the function file whose inputs must be t and y and whose output must be a column vector representing dy/dt;that is f(t,y). tspan contains the starting and ending values of the independent variable t. y0 is the value

42 42 6. Numerical Methods for Differential Equations Ex: Response of an RC circuit suppose the value of RC = 0.1 second. Using the numerical method to find the free response for the case where the applied voltage v is 0 and the initial capacitor voltage is y(0)=2 volts

43 43 6. Numerical Methods for Differential Equations rccirc.m function ydot=rccirc(t,y) ydot = -10*y; test2.m clear; [t,y] =ode45(‘rccirc’, [0,0.4],2); y_true = 2*exp(-10*t); plot(t,y,’o’,t,y_true) xlabel(‘Time(sec)’) ylabel(‘Capacitor Voltage’)

44 44 6. Numerical Methods for Differential Equations Ex: The following equation describes the motion of a mass connected to a spring with viscous friction acting between the mass and the surface. Another force f(t) also acts on the mass. Let We have These two equations can be written as one matrix equation as follows:

45 45 6. Numerical Methods for Differential Equations msd.m function xdot = msd(t,x) % function file for mass with spring and damping % position is first variable, velocity is second variable. global c f k m A=[0,1;-k/m,-c/m]; b=[0;1/m]; xdot=A*x+b*f; test.m global c f k m m=1;c=2;k=5;f=10; [t,x]=ode23(‘msd’,[0,5],[0,0]); plot(t,x), xlabel(‘Time(sec)’),… ylabel(‘Displacement (m) and Velocity (m/sec)’),… gtext(‘Displacement’), gtext(‘Velocity’)

46 46 6. Numerical Methods for Differential Equations

47 47 6. Numerical Methods for Differential Equations

48 48 Summary


Download ppt "1 Matlab for Engineering Applications Introduced by Jen-Yang Chen Department of Electronic Engineering Ming Chuan University."

Similar presentations


Ads by Google