Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Introduction to Matlab-2 Laboratoire Mathématiques, Informatique et Applications.

Similar presentations


Presentation on theme: "1 Introduction to Matlab-2 Laboratoire Mathématiques, Informatique et Applications."— Presentation transcript:

1 1 Introduction to Matlab-2 Laboratoire Mathématiques, Informatique et Applications

2 2 Desktop Tools (Matlab v6)  Command Window –type commands  Workspace –view program variables –clear to clear –double click on a variable to see it in the Array Editor  Command History –view past commands –save a whole session using diary  Launch Pad –access tools, demos and documentation

3 3 Matlab Files (.m)  Use predefined functions or write your own functions  Reside on the current directory or the search path –add with File/Set Path  Use the Editor/Debugger to edit, run

4 4 Matrices  a vector x = [1 2 5 1] x = 1 2 5 1 a matrix x = [1 2 3; 5 1 4; 3 2 -1] x = 1 2 3 5 1 4 3 2 -1 transpose y = x ’ y = 1 2 5 1

5 5 Matrices  x(i,j) subscription  whole row  whole column y=x(2,3) y = 4 y=x(3,:) y = 3 2 -1 y=x(:,2) y = 2 1 2

6 6 Operators (arithmetic) +addition -subtraction *multiplication /division ^power ‘complex conjugate transpose.*element-by-element mult./element-by-element div.^element-by-element power.‘transpose

7 7 Operators (relational, logical) ==equal ~=not equal <less than <=less than or equal >greater than >=greater than or equal &AND |OR ~NOT pi3.14159265… jimaginary unit, isame as j

8 8 Generating Vectors from functions  zeros(M,N)MxN matrix of zeros  ones(M,N)MxN matrix of ones  rand(M,N)MxN matrix of uniformly distributed random numbers on (0,1) x = zeros(1,3) x = 0 0 0 x = ones(1,3) x = 1 1 1 x = rand(1,3) x = 0.9501 0.2311 0.6068

9 9 Operators [ ]concatenation ( )subscription x = [ zeros(1,3) ones(1,2) ] x = 0 0 0 1 1 x = [ 1 3 5 7 9] x = 1 3 5 7 9 y = x(2) y = 3 y = x(2:4) y = 3 5 7

10 10 Matlab Graphics x = 0:pi/100:2*pi; y = sin(x); plot(x,y); xlabel('x = 0:2\pi'); ylabel('Sine of x'); title('Plot of the Sine Function');

11 11 Multiple Graphs t =0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2); grid on;

12 12 Multiple Plots t =0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1); plot(t,y1); subplot(2,2,2); plot(t,y2);

13 13 If Statements IF expression statements ELSEIF expression statements ELSE statements END

14 14  Example clear all; close all; n=10; x=1:n; y=zeros([1,n]); for k=1:n y(k) = 2*k; end plot(x,y);

15 15 Homework  Generate a tree structure for the system equation y=sin(ax) + bx knowing that x is the system input and y is the system output. X and y are arrays of n values. Assume n = 100;  Generate a random sequence from -2 to 2 to be used as the system input x using the randn command.  Plot the input versus the output of the above system.

16 16 Solution clear all; close all; x=2-4*rand(1,100); a=2; b=3; y=sin(a*x) + b*x; subplot(2,1,1); plot(x); grid; title('system input'); subplot(2,1,2); plot(y,'r'); grid; title('system output');

17 17

18 18 Graph Functions (summary)  plotlinear plot  gridadd grid lines  xlabeladd X-axis label  ylabel add Y-axis label  titleadd graph title  subplotdivide figure window  figurecreate new figure window  pausewait for user response

19 19 Math Functions  Elementary functions (sin, cos, sqrt, abs, exp, log10, round) –type help elfun  Advanced functions (bessel, beta, gamma, erf) –type help specfun –type help elmat

20 20 Scripts  Matlab editor  Use scripts to execute a series of Matlab commands Matlab Desktop Press to create new m-file in the matlab editor

21 21 Functions function f=myfunction(x,y) f=x+y;  save it in myfunction.m  call it with y=myfunction(x,y)

22 22 Functions  Programming in Matlab.  Users can write functions which can be called from the command line.  Functions can accept input variable(s)/matrice(s) and will output variable(s)/matrice(s).  Functions will not manipulate variable(s)/matrice(s) in the Matlab Workspace.  In Matlab functions closely resemble scripts and can be written in the Matlab editor. Matlab functions have the function keyword.  Remember that the filename of a function will be its calling function name.  Don’t overload any built-in functions by using the same filename for your functions or scripts!  Functions can be opened for editing using the open command. Many built-in Matlab functions can also be viewed using this command.

23 23 >> I=iterate(5) I = 1 4 9 16 25 Functions (continued) output input function name for statement block function keyword help lines for function Access the comments of your Matlab functions >> help iterate Make sure you save changes to the m-file before you call the function!

24 24 >> [i j]=sort2(2,4) i = 4 j = 2 >> Functions (continued) Functions can have many outputs contained in a matrix Remember to use the Matlab help command for syntax >> help if if statement block

25 25 More flow control Method is linear >> i = 4 i = 16 i = 256 While statement blockSwitch statement block Without ; to print output

26 26 Debugging  Set breakpoints to stop the execution of code >> [i j]=sort2(2,4) K>> K>> whos Name Size Bytes Class a 1x1 8 double array b 1x1 8 double array Grand total is 2 elements using 16 bytes K>> a a = 2 K>> return i = 4 j = 2 Click mouse on the left of the line of code to create a breakpoint local function workspace exit debug mode Debug menus

27 27 Visualisation - plotting data >> figure % create new figure >> t=0:pi/12:8*pi; >> y=cos(t); >> plot(t,y, ‘ b.-') Investigate the function >> y=A*cos(w*t+phi); for different values of phi (eg: 0, pi/4, pi/3, pi/2), w (eg: 1, 2, 3, 4) and A (eg: 1, 0.5, 2). Use the hold on Matlab command to display your plots in the same figure. Remember to type hold off to go back to normal plotting mode. Try using different plot styles (help plot) A = amplitude phi = phase w = angular frequency = 2*pi*frequency Plot style

28 28 Flow Control A=3; B=2; if A > B 'greater' elseif A < B 'less' else 'equal' end for x = 1:10 r(x) = x; end if statement switch statement for loops while loops continue statement break statement

29 29 Miscellaneous  Loading data from a file –load myfile.dat  Definition – x = [1 2 5 1];

30 30 Getting Help  Using the Help Browser (.html,.pdf) –View getstart.pdf, graphg.pdf, using_ml.pdf  Type –help –help function, e.g. help plot  Running demos –type demos –type help demos

31 31 >> help stem STEM Discrete sequence or "stem" plot. STEM(Y) plots the data sequence Y as stems from the x axisterminated with circles for the data value. STEM(X,Y) plots the data sequence Y at the values specified in X. STEM(...,'filled') produces a stem plot with filled markers. STEM(...,'LINESPEC') uses the linetype specified for the stems and markers. See PLOT for possibilities. H = STEM(...) returns a vector of line handles. See also PLOT, BAR, STAIRS.

32 32 Random Numbers x=rand(100,1); stem(x); hist(x,100)

33 33 Coin Tosses  Simulate the outcomes of 100 fair coin tosses x=rand(100,1); p=sum(x<0.5)/100 p = 0.5400  Simulate the outcomes of 1000 fair coin tosses x=rand(1000,1); p=sum(x<0.5)/1000 p = 0.5110

34 34 Coin Tosses  Simulate the outcomes of 1000 biased coin tosses with p[Head]=0.4 x=rand(1000,1); p=sum(x<0.4)/1000 p = 0.4160

35 35 Sum of Two Dies  Simulate 10000 observations of the sum of two fair dies

36 36 Sum of Two Dies for i=2:12 z(i)=sum(y==i)/10000 end bar(z)

37 Boolean Operations » x=[0 1 1]; y=[1 1 1]; » and(x,y) » ans = » 0 1 1 » or(x,y) » ans = » 1 1 1 » x=[0 1 1]; y=[1 1 1]; » and(x,y) » ans = » 0 1 1 » or(x,y) » ans = » 1 1 1 1 = TRUE 0 = FALSE »bool_ops

38 Solving Simultaneous Equations using “Left Division”  If [A] is square matrix (m = n):  For overdetermined system (m>n): using Least squares regression “curve fit” of data Warning if rank deficient (dependent columns) - solution not unique  For undetermined system (m<n): using QR factorization with column pivoting Never unique [A]{x} = {b} {x} = ? {x} = [A] -1 {b} »x = inv(A)*b; »x = A\b; »x = inv(A)*b; »x = A\b; Error if singular Warning if nearly singular [A] = mxn {x} = nx1 {b} = mx1 »x = A\b;

39  Solve this set of simultaneous equations: Example: Solving Equations »A = [-1 1 2; 3 -1 1;-1 3 4]; »b = [2;6;4]; »x = inv(A)*b x = 1.0000 2.0000 »x = A\b x = 1.0000 2.0000 »A = [-1 1 2; 3 -1 1;-1 3 4]; »b = [2;6;4]; »x = inv(A)*b x = 1.0000 2.0000 »x = A\b x = 1.0000 2.0000 -x 1 + x 2 + 2x 3 = 2 3x 1 - x 2 + x 3 = 6 -x 1 + 3x 2 + 4x 3 = 4

40 40 Return to our example clear all; close all; n=20; x=rand(1,n); x1= [0 x(1:n-1)]; x2= [0 0 x(1:n-2)]; a=2; b=5; y= a*x1 + b*x2; figure; plot(y,'r'); grid; title('system output');

41 String Arrays  Created using single quote delimiter (')  Each character is a separate matrix element (16 bits of memory per character)  Indexing same as for numeric arrays »str = 'Hi there,' str = Hi there, »str2 = 'Isn''t MATLAB great?' str2 = Isn't MATLAB great? »str = 'Hi there,' str = Hi there, »str2 = 'Isn''t MATLAB great?' str2 = Isn't MATLAB great? 1x9 vector str = Hithere,

42 »str ='Hi there,'; »str1='Everyone!'; »new_str=[str, ' ', str1] new_str = Hi there, Everyone! »str2 = 'Isn''t MATLAB great?'; »new_str2=[new_str; str2] new_str2 = Hi there, Everyone! Isn't MATLAB great? »str ='Hi there,'; »str1='Everyone!'; »new_str=[str, ' ', str1] new_str = Hi there, Everyone! »str2 = 'Isn''t MATLAB great?'; »new_str2=[new_str; str2] new_str2 = Hi there, Everyone! Isn't MATLAB great? 1x19 vector 1x9 vectors String Array Concatenation Using [ ] operator: Each row must be same length Row separator: semicolon (;) Column separator: space / comma (,) For strings of different length: STRVCAT STR2MAT »new_str3 = strvcat(str, str2) new_str3 = Hi there, Isn't MATLAB great? »new_str3 = strvcat(str, str2) new_str3 = Hi there, Isn't MATLAB great? 2x19 matrix (zero padded) 1x19 vectors

43 Working with String Arrays String Comparisons – STRCMP - compare whole strings – STRNCMP - compare first ‘N’ characters – FINDSTR - finds substring within a larger string Converting between numeric & string arrays: – NUM2STR - convert from numeric to string array – STR2NUM - convert from string to numeric array

44 44 End of Lecture


Download ppt "1 Introduction to Matlab-2 Laboratoire Mathématiques, Informatique et Applications."

Similar presentations


Ads by Google