440 likes | 618 Views
Introduction to Matlab-2. Laboratoire Mathématiques, Informatique et Applications. 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
E N D
Introduction to Matlab-2 Laboratoire Mathématiques, Informatique et Applications
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
Matlab Files (.m) • Use predefined functions or write your own functions • Reside on the current directoryor the search path • add with File/Set Path • Use the Editor/Debugger to edit, run
Matrices • a vectorx = [1 2 5 1] x = 1 2 5 1 a matrixx = [1 2 3; 5 1 4;3 2 -1] x = 1 2 3 5 1 4 3 2 -1 transposey = x’y = 1 2 5 1
Matrices y=x(2,3) y = 4 y=x(3,:) y = 3 2 -1 y=x(:,2) y = 2 1 2 • x(i,j) subscription • whole row • whole column
Operators (arithmetic) + addition - subtraction * multiplication / division ^ power ‘ complex conjugate transpose .* element-by-element mult ./ element-by-element div .^ element-by-element power .‘ transpose
Operators (relational, logical) == equal ~= not equal < less than <= less than or equal > greater than >= greater than or equal & AND | OR ~ NOT • pi 3.14159265… • j imaginary unit, • i same as j
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 = 111 x = rand(1,3) x = 0.9501 0.2311 0.6068 Generating Vectors from functions
[ ] 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 Operators
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');
t =0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2); grid on; Multiple Graphs
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);
If Statements IF expression statements ELSEIF expression statements ELSE statements END
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);
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.
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');
Graph Functions (summary) • plot linear plot • grid add grid lines • xlabel add X-axis label • ylabel add Y-axis label • title add graph title • subplot divide figure window • figure create new figure window • pause wait for user response
Math Functions • Elementary functions (sin, cos, sqrt, abs, exp, log10, round) • typehelp elfun • Advanced functions (bessel, beta, gamma, erf) • typehelp specfun • typehelp elmat
Scripts • Matlab editor • Use scripts to execute a series of Matlab commands Matlab Desktop Press to create new m-file in the matlab editor
Functions function f=myfunction(x,y) f=x+y; • save it in myfunction.m • call it with y=myfunction(x,y)
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.
Functions (continued) function name input output >> I=iterate(5) I = 1 4 9 16 25 function keyword help lines for function for statement block Access the comments of your Matlab functions >> help iterate Make sure you save changes to the m-file before you call the function!
Functions (continued) Functions can have many outputs contained in a matrix >> [i j]=sort2(2,4) i = 4 j = 2 >> if statement block Remember to use the Matlab help command for syntax>> help if
More flow control While statement block Switch statement block Without ; to print output i = 4 i = 16 i = 256 Method is linear>>
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 Debug menus local function workspace exit debug mode Click mouse on the left of the line of code to create a breakpoint
Visualisation - plotting data >> figure % create new figure >> t=0:pi/12:8*pi; >> y=cos(t); >> plot(t,y,‘b.-') Plot style 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 = amplitudephi = phasew = angular frequency = 2*pi*frequency
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
Miscellaneous • Loading data from a file • load myfile.dat • Definition • x = [1 2 5 1];
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
>> 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.
Random Numbers x=rand(100,1); stem(x); hist(x,100)
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
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
Sum of Two Dies • Simulate 10000 observations of the sum of two fair dies
Sum of Two Dies for i=2:12 z(i)=sum(y==i)/10000 end bar(z)
Boolean Operations • 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
Solving Simultaneous Equationsusing “Left Division” [A] = mxn {x} = nx1 {b} = mx1 • 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 = inv(A)*b; • x = A\b; {x} = [A]-1{b} Error if singular Warning if nearly singular • x = A\b; • x = A\b;
Example: Solving Equations • Solve this set of simultaneous equations: • A = [-1 1 2; 3 -1 1;-1 3 4]; • b = [2;6;4]; • x = inv(A)*b • x = • 1.0000 • -1.0000 • 2.0000 • x = A\b • x = • 1.0000 • -1.0000 • 2.0000 -x1 + x2 + 2x3 = 2 3x1 - x2 + x3 = 6 -x1 + 3x2 + 4x3 = 4
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');
1x9 vector H i t h e r e , str = 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?
String Array Concatenation Using [ ] operator: Each row must be same length Row separator: semicolon (;) Column separator: space / comma (,) • 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? 1x9 vectors 1x19 vectors 1x19 vector 2x19 matrix • For strings of different length: • STRVCAT • STR2MAT • new_str3 = strvcat(str, str2) • new_str3 = • Hi there, • Isn't MATLAB great? 2x19 matrix (zero padded)
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