INTRODUCTION TO MATLAB LAB# 01 Introduction to Matlab • What is Matlab? – Matlab is a commercial “MATrix LABoratory” package by Mathworks, which operates as an interactive programming environment with graphical output. – The MATLAB programming language is exceptionally straight forward since almost every data object is assumed to be an Array. – In engineering MATLAB is displacing popular programming languages, due to its interactive interface, reliable algorithmic foundation, fully extensible environment and availability of different tool boxes. Introduction to MATLAB • Entering and Running MATLAB – On a system running Microsoft Windows double click on the Matlab icon to launch Matlab. – A command window will appear with the prompt >> you are now in MATLAB. • Leaving Matlab – A MATLAB session may be terminated by simply typing >> quit or by typing >>exit at the MATLAB prompt. • Online Help Online help is available from the MATLAB prompt both generally and for specific commands. >> help >> help demo Desktop Tools (Matlab v7) • 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 Variables • MATLAB is case sensitive, that is ‘a’ is not the same as ‘A’ – MATLAB has built in variables like pi, eps and ans. – The variable ans will keep track of the last output which was not assigned to another variable. • Variable Assignment: – The equality sign is used to assigned values to variables. • >> x = 3 y=x^2 – Out put can be suppressed by appending a semicolon to the command lines. • >> x = 3 ; y=x^2; Variables • Active Variables: – Who • Removing Variables – Clear x – Clear • Saving and Restoring Variables – Save filename – Load filename Variable Arithmetic • Operator precedence – 2 + 3 *4 ^ 2 • Double Precision Arithmetic – Normally the results will be displayed in a shorter form. • a = sqrt( 2 ) >> a = 1.4142 – Format long • b = sqrt ( 2 ) >> b = 1.41421356………. – Format short • Command Line Editing – The arrow keys allow “ command line editing” Built in Mathematical Functions Functions Meaning Examples Sin sine sin ( pi )=0.0 Cos cosine cos ( pi )=1.0 Tan tangent tan ( pi / 4)=1.0 Exp exponential exp(1.0)=2.7183 log natural log log(2.7183)=1.0 • Arguments to trigonometric functions are given in radians. – x= pi / 3; – sin( x ) ^ 2 + cos ( x ) ^ 2 = ? Matrices • The element within a row of a matrix may be separated by a commas as well as a blank. • The elements of a matrix being created are enclosed by brackets. • A matrix is entered in “row major order” [i.e. all of the first row, then all of the second row; etc]; • Rows are separated by semicolon [or a new line], and the elements of the row may be separated by either a comma or space. • The following commands will create a 3 x 3 matrix and assigned it to the variable A. – >> A = [1 2 3; 4 5 6; 7 8 9]; or A = [1,2,3;4,5,6;7,8,9] – >> A = [ 1 2 3 4 5 6 7 8 9] Matrices • The matrix element located in the i-th row and j-th column of A is referred to in the usual way: – >> A (1 , 2), A ( 2 , 3) • Matrices can be easily modified: – A ( 2 , 3 ) = 10; • Building Matrices from a Block: – Large matrices can be assembled from smaller matrix blocks i.e. • C = [A;10 11 12]; • [A; A; A] • [A, A, A] • >> B = [A, zeros(3,2); zeros(2,3), eye( 2 ) ] ? Built in Matrix Functions Function Description diag eye magic ones rand return diagonal M.E as a vector identity matrix magic squares matrix of ones randomly generated matrix zeros matrix of zeros Built in Matrix Functions • Matrices of Random Entries: – >> rand ( 3 ) – >> rand ( m , n ) • Magic Squares: – A magic square is a square matrix which has equal sums along all its rows and columns. – >> magic ( 4 ) • Matrix of Ones: – >> eye ( m , n ) – >> eye ( n ) • Matrices of Zeros: – >> zeros ( m , n ) – >> zeros ( n ) • Diagonal Matrices: – >> diag (A) • diag ( diag ( A ) ) ? Matrix Operations + * ^ ‘ / Addition Subtraction Multiplication Power Transpose Division .* ./ .^ .‘ element-by-element mul element-by-element div element-by-element power transpose * If the sizes of the matrices are incompatible for the matrix operation, an error message will result. Matrix Operations • • • • • Matrix Transpose: – >> A’ Matrix Addition / Subtraction: – A + B, A – B Matrix Multiplication; – A * B , B * A. Round Floating Point Numbers to Integers: – >> f = [-.5 .1 .5 ] – round (f) – ceil (f) – floor (f) – sum (f) – prod (f) Matrix Element Level Operations: – The matrix operation of addition and subtraction are already operates on an element by element basis but other operation given above do not. – Matlab has a convention in which a dot in front of the operations is used. – i.e [1 , 2 , 3 , 4 ] . * [ 1 , 2 , 3 , 4 ] – [1,2,3,4 ].^ 2 Operators (relational, logical) == ~= < <= > >= equal not equal less than less than or equal greater than greater than or equal & | ~ AND OR NOT Branching Constructs • If – end Construct: if < condition >, • If - elseif - end Construct: if < condition1 >, < program > end • < program 1> elseif <condition2> < program2 > If - else - end Construct: if < condition 1 >, < program 1> else < program2 > end end Looping Constructs • For Loops: for i = 1 : n , < program>, end • While Loops: while < condition >, < program >, end • Nested For Loops: for i = 1 : n , for j = 1 : n , A(i,j) = i/j ; end end Matlab M-files • Matlab commands can be run from one file without having to enter each command one by one at Matlab prompt. • In order to use the programs later in Matlab they are to be saved first. • For this purpose programs should be written in the editor / debugger. – In command window go to File menu, new and select M-file. – Code your algorithm – Execute it from the command window by typing file name Matlab User Defined Function • Matlab User Defined Function can have an input and output. • Arguments can be passed to a function for computation • For this purpose programs should be written in the editor / debugger. – In command window go to File menu, new and select M-file. – function add x = 3; z=x+y y = 5; – Save the file and write add at the command prompt – function addv (x,y) Z=x+y – Save the file and write addv(5,6) at the command prompt – % is used for commenting in front of a statement Input/ Output • Request User Input – data=input(‘message’); – data=input(‘message’,’s’) • Ouput Data – disp(‘message’) – disp(variable_name) 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') Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on Multiple Graphs x = 0 : .01 : 2 * pi; y1= sin (x); y2 =sin (2*x); y3 = sin (4*x); plot(x,y1,‘--',x,y2,‘-‘,x,y3,‘+') grid title ('Dashed line and dotted line graph') 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) Three Dimensional Graphics x = -1:.1:1 ; y = -1:.1:1; for i=1:1:length(x) for j=1:1:length(y) z(i,j)=x(i)^2+y(j)^2; end end mesh(z); Graph Functions (summary) • • • • • • • • • • • • • plot (x,y) plot (x,y1,x,y2) mesh(z) stem (x) xlabel (‘X-axis label ’) ylabel (‘Y-axis label ’) title (‘title of plot’) subplot (m,n,p) grid hold zoom figure pause linear plot multiple plots on the same graph 3-D graph discrete plot add X-axis label add Y-axis label add graph title divide figure window add grid lines hold current graph in the figure allow zoom in/out using mouse create new figure window wait for user response