Matlab

1,075 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,075
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
105
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Matlab

  1. 1. MATLAB Basic MATLAB - matrices operators script and function files flow control plotting Basic MATLABoptional windows workspace current directory s here command window Screen shot of the Matlab window 1
  2. 2. MATLAB Variablesall variables stored in 32bit floating point formatno distinction between real and integer >>a = 3; same assignment for “a” >>a = 3.0;Matlab is case sensitive >>A=3; A≠a >>a=2; MATLAB Variablescan use numbers and underscore in variable names >>case34=6.45; OK >>case_34=6.45; names must start with a letter >>34case=23.45; syntax error string (text) variables enclosed in single quotes. The variable is stored as array of characters >>title=‘This is the title’; 2
  3. 3. MATLAB Variablesif a variable is defined,typing the variable name returns its value >>a=45.57; >>a a= 45.57to clear a variable from memory >>a=4 >>clear a MATLAB VariablesMatlab will “echo” commands unless a semi-colon is used>>a=23.2;>>>>a=23.2a= Matlab echoes the command 23.2>> 3
  4. 4. MATLAB Variables Vectors column vectors row vectors ⎧1 ⎫ ⎪ ⎪ a = ⎨2 ⎬ a = {1 2 3} ⎪3 ⎪ ⎩ ⎭ >>a=[1;2;3]; >>a=[1,2,3]; >>a >>a a= a= 1 1 2 3 2 3 use commause semi-colonto separate rows to separate columns MATLAB Variables Matrices ⎡1 2 3⎤2-dimensional matrices a=⎢ ⎥ ⎣4 5 6⎦ >>a=[1,2,3;4,5,6]; >>a a= 1 2 3 4 5 6again, separate columns with commas and rowswith semi-colons 4
  5. 5. MATLAB VariablesIndexing Matrix elements A vector is a special type of matrix row vector is a 1 x n matrix, 1 row n columns column vector is a n x 1 matrix, n rows 1 column >>a=[1,2,3]; >>a(2) could also reference by a(1,2) ans = note, a(2,1) would produce an error 2 because “a” only has one row MATLAB Variables Indexing Matrix elements more examples ⎡1 2 3⎤ >>a=[1,2,3;4,5,6]; a=⎢ ⎥ ⎣4 5 6⎦ assigning addressing >>a(2,2)=9; >>a(2,3) >>a ans = a= 6 1 2 3 4 9 6 5
  6. 6. MATLAB Variables Complex-valued numbers Typically, the variable “i” or “j” is used to represent the complex variable; e.g. i = −1 Then, a complex number is represented as z = a + ib Re(z) = a Im(z) = b MATLAB Variables Complex-valued numbers Unless i or j has been previously defined, Matlab assigns i and j the complex variable value In Matlab, a complex variable is represented in the following format >>z=23+i*56; >>z=23+j*56; >>z >>z z= z= 23.00 + 56.00i 23.00 + 56.00iMatlab always uses the symbol “i” to represent acomplex number 6
  7. 7. MATLAB Operations Basic operations addition + subtraction - multiplication * division right division / left division ? >>a=3;b=4; c1=0.75 >>c1=a/b; so, be careful! c2=1.3333…. >>c2=ab; MATLAB Operations Mixed Real and Complex valued Variablesif both variables are real-valued, a real-valued resultis obtainedif one variable is complex-valued, Matlab recaststhe real variable as complex and then performs theoperation. The result is complex-valuedhowever, the type casting is done internally, thereal-valued variable remains real after the operation 7
  8. 8. MATLAB Operations Other (Scalar) OperationsMath representation Matlab interpretation z = yx >>z=y^x; y = ex >>y=exp(x); y = ln(x) >>y=log(x); y = log(x) >>y=log10(x) y = sin(x) y = sin −1 (x) >>y=sin(x); >>y=asin(x); y = cos(x) y = cos −1 (x) >>y=cos(x); >>y=acos(x); y = tan(x) y = tan −1 (x) >>y=tan(x); >>y=atan(x); MATLAB Operations MatricesOnly matrices of the same dimension can be added and subtractedFor multiplication, the inner dimensions must be the same ⎡4 5⎤ ⎡1 2 3⎤ ⎡2 3 4⎤ A=⎢ ⎥ B=⎢ ⎥ C = ⎢6 7 ⎥ ⎣4 5 6⎦ ⎢ ⎥ ⎣5 6 7 ⎦ ⎢8 9 ⎥ ⎣ ⎦ No error Error >>D=A+B; >>D=A+C; >>D=A-B; >>D=A*B; >>D=A*C; Matrix multiplication >>D=B*A; >>D=C*A; not commutative 8
  9. 9. MATLAB Operations Left() and Right(/) Matrix “division” Math representation Matlab interpretation C = A −1B >>C=AB; C = BA −1 >>C=B/A; Remember, A must be square and full rank (linearly independent rows/columns) MATLAB Operations Matrix Transpose Math representation Matlab interpretation C = AT >>C=A’;For complex-valued matrices, complex conjugate transpose ⎡1 2 3⎤ A=⎢ ⎥ a = [1 + j2 3 + j4] ⎣4 5 6⎦ >>B=A’; >>b=a’; ⎡1 4 ⎤ B = ⎢2 5⎥ ⎡1 − j2 ⎤ ⎢ ⎥ b=⎢ ⎥ ⎢3 6⎥ ⎣ ⎦ ⎣3 − j4 ⎦ 9
  10. 10. MATLAB OperationsConcatenation MATLAB Operations Deleting Rown and Columns 10
  11. 11. MATLAB Operations The ‘.’ operator .* does element by element multiplication ./ and . : Element by element left and right division respectavely MATLAB Operations The COLON operator : The expression 1:10 is a row vector containing numbers 1 to 10 1 2 3 …… 10 To obtain non unit spacing , specify an increment For Example 1:2:10 gives 1 3 5 7 9Subscript expressions involving ‘:’ refer to a part of a matrix A(1:k,j) is the first k elements of the jth column of A 11
  12. 12. MATLAB Operations Some other useful functions :The sum function : Returns a row vector containing sum of all elements in each column.sum(A)ans = 34 34 34 34The diag function : Returns a row vector containing the principal diagonal elementsDiag (A)ans = 16 10 7 1 MATLAB Operations The Random number generatorsRand : Generates random numbers following a uniform distributionRandn : Generates random numbers following a normal distribution (mean 0 ,variance=1 , sd =1 ) 12
  13. 13. MATLAB Operations Some Key Help commandsHelp elfun : Elementary mathematical functionsHelp specfun: Advanced mathematical functionsHelp elmat: Advanced matrix functions MATLAB m-files Two types of m-files script files collection of commands that Matlab executes when the script is “run” function files collection of commands which together represent a function, a procedure or a method Both types are separate files with a “.m” extension 13
  14. 14. MATLAB m-files To create an m-file, open the Matlab text editor Click on the “page” icon The Matlab text editor window will open MATLAB m-files Script FilesOn the command line In the script file named test.m >>x=3.0; >>y=x^2; >>y y = 9.0 >> On the command line >>test y = 9.0 >> 14
  15. 15. MATLAB m-files Script Files script files share the workspace memory test.m script >>x=5.0; >>test >>y y = 25.0 >> MATLAB m-files Script Files script files can call other script files inner.m script>>outtery = outter.m script 36.0>> 15
  16. 16. MATLAB m-files Function FilesMatlab identifies function files from script files byusing the “function” and “return” keywordsSyntax: function [list of outputs] = filename (inputs) the name of the function file must be the same name as the function MATLAB m-files Function Files The function file x2.m >>r=3; >>h=x2(4.2); >>d=x2(r); >>h >>d h = d = 17.64 9.0 >> >> 16
  17. 17. MATLAB m-files Function Files Multiple Inputs and Outputsoutputs in square brackets, [ ] inputs in parentheses ( ) MATLAB m-files Function Files variables created in the function are not retained in the workspace, except for the output variables the function does not have access to workspace variables, except for the inputs variables passed to the function are “copies” of the workspace variables. Changing their value inside the function has no effect on their value in the workspace. 17
  18. 18. MATLAB Flow Control The “while” and “if” statementswhile expression if expression if expression statements statements statements1end end else statements2 end Matlab evaluates expression as logical “true” or “false” “false” equivalent to zero “true” equivalent to any non-zero number statements, any valid Matlab command MATLAB Flow Control evaluating expressionany valid equation conditional operators a=4; == equal to b=5; < less than c=5; > greater than if a+b “True” <= less than or equal to if b-c “False” >= greater than or equal towatch out for round-off ~= not equal toand word length error logical operators if sin(0) “False” & and if sin(pi) “True” | or sin(pi) = 1.22e-16 while(3<=a)&(a<=5) 18
  19. 19. MATLAB Flow Control The “for” statement for index = start : [increment :] end statements end increment is optional, if increment is not specified increment defaults to 1index, start, increment, and end do not need to be integervaluedindex can be incremented positive (increment > 0)or negative (increment < 0)loop stops when index > end (or index < end) MATLAB Flow Control example script file to cycle through x values function file to generate the y values 19
  20. 20. MATLAB Plotting Basic 2D plotting functions plot(x1,y1[,x2,y2,x3,y3.....]) xlabel(‘x axis name’) ylabel(‘y axis name’) title(‘graph name’) Additional functions grid on grid off axis([xmin,xmax,ymin,ymax]) MATLAB Plotting example y = sin(t)the “plot” function alone 20
  21. 21. MATLAB Plotting example y = sin(t) script file to generate a graph of y = sin(t) MATLAB Plotting example y = sin(t)function file to generatea graph of y = sin(t)>>graphsin>> 21
  22. 22. MATLAB Plotting Adding a Legend for multiple graphs“legend” remembersthe order the graphswere plotted MATLAB Plotting Plot function in some detail•PLOT(X,Y) plots vector Y versus vector X•If X is a scalar and Y is a vector, length(Y) disconnected points are plotted.•If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)). Additional functions grid on grid off axis([xmin,xmax,ymin,ymax]) 22
  23. 23. b blue . point - solid g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star y yellow s square k black d diamond v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram MATLAB Plotting 3D PlotsThe plot3 command Three dimensional analog of plot where x, y and z are three vectors of the same length, plots a line in 3D-space through the points whose coordinates are the elements of x, y and z. Character string can be used with the plot3 command just as with the plot command 23
  24. 24. Thank you 24

×