Matlab

2,593 views

Published on

matlab study

Published in: Education
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,593
On SlideShare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
344
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Matlab

  1. 1. 1C Language is Simplest.
  2. 2. 2What may be the size of the program forwriting a C code that generates sinwave?
  3. 3. 3But we can do the same by only threelines.
  4. 4. x=0.1:0.1:10; 4b=sin(x);Plot(x,b)------ nocomputationalcomplexity
  5. 5. 5That is the beauty we have as anengineer.Name is MATLAB
  6. 6. Recent Trends in Computational techniques for Engineering 6 Use of MATLAB in EngineeringProf. Ashish M. KothariDepartment of Electronics & Communication EngineeringAtmiya Institute of Technology & Science, Rajkot
  7. 7. Topics.. 7What is MATLAB ??Basic Matrix OperationsScript Files and M-filesSome more Operations and FunctionsPlotting functions ..
  8. 8. Topics.. 8What is MATLAB ??Basic Matrix OperationsScript Files and M-filesSome more Operations and FunctionsPlotting functions
  9. 9. MATLAB 9“MATrix LABoratory”Powerful, extensible, highly integratedcomputation, programming, visualization, andsimulation packageWidely used in engineering, mathematics, andscience
  10. 10. MATLAB 10Everything in MATLAB is a matrix !
  11. 11. MATLAB- Starting & Quiting 11Starting MATLABOn a Microsoft Windows platform, to start MATLAB, double-click theMATLAB shortcut icon on your Windows desktop.On Linux, to start MATLAB, type matlab at the operating system prompt.After starting MATLAB, the MATLAB desktop opens – see “MATLABDesktop”.You can change the directory in which MATLAB starts, define startupoptions including running a script upon startup, and reduce startup time insome situations.
  12. 12. MATLAB- Starting & Quiting 12Quiting MATLABTo end your MATLAB session, select Exit MATLAB from theFile menu in the desktop, or type quit in the CommandWindow.
  13. 13. The MATLAB Desktop 13
  14. 14. MATLAB Variable 15Variable names ARE case sensitiveVariable names can contain up to 63 characters (as ofMATLAB 6.5 and newer)Variable names must start with a letter followed by letters,digits, and underscores.
  15. 15. MATLAB Variable 16>> 16 + 24 no declarations neededans = 40>> product = 16 * 23.24 mixed data typesproduct = 371.84 semi-colon suppresses output of>> product = 16 *555.24; the calculation’s result>> productproduct = 8883.8
  16. 16. MATLAB Variable 17>> clear clear removes all variables;>> product = 2 * 3^3;>> comp_sum = (2 + 3i) + (2 - 3i); clear x y removes only x and y>> show_i = i^2; complex numbers (i or j) require>> save three_things no special handling>> clear>> load three_things>> who save/load are used toYour variables are:comp_sum product show_i retain/restore workspace variables>> productproduct = 54 use home to clear screen and put>> show_i cursor at the top of the screenshow_i = -1
  17. 17. MATLAB Special Variables 18ans Default variable name for resultspi Value of πeps Smallest incremental numberinf InfinityNaN Not a number e.g. 0/0i and j i = j = square root of -1realmin The smallest usable positive real numberrealmax The largest usable positive real number
  18. 18. Topics.. 19What is MATLAB ??Basic Matrix OperationsScript Files and M-filesSome more Operations and FunctionsPlotting functions ..
  19. 19. Math & Assignment Operators 20Power ^ or .^ e.g a^b or a.^bMultiplication * or .* e.g a*b or a.*bDivision / or ./ e.g a/b or a./b or or . e.g ba or b.a NOTE: 56/8 = 856 - (unary) + (unary) Addition + a+b Subtraction - a-b Assignment = a=b (assign b to a)
  20. 20. Other MATLAB symbols 21>> prompt... continue statement on next line, separate statements and data% start comment which ends at end of line; (1) suppress output (2) used as a row separator in a matrix: specify range
  21. 21. MATLAB Relational Operators 22MATLAB supports six relational operators.Less Than <Less Than or Equal <=Greater Than >Greater Than or Equal >=Equal To ==Not Equal To ~=
  22. 22. MATLAB Logical Operators 23MATLAB supports three logical operators.not ~ % highest precedenceand & % equal precedence with oror | % equal precedence with and
  23. 23. MATLAB Matrices 24MATLAB treats all variables as matrices. For our purposesa matrix can be thought of as an array, in fact, that is howit is stored.Vectors are special forms of matrices and contain only onerow OR one column.Scalars are matrices with only one row AND one column
  24. 24. MATLAB Matrices 25 A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:» a_value=23a_value = 23
  25. 25. MATLAB Matrices 26 A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):» rowvec = [12 , 14 , 63]rowvec = 12 14 63
  26. 26. MATLAB Matrices 27 A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):» colvec = [13 ; 45 ; -2]colvec = 13 45 -2
  27. 27. MATLAB Matrices 28 A matrix can be created in MATLAB as follows (note the commas AND semicolons):» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]matrix = 1 2 3 4 5 6 7 8 9
  28. 28. Extracting a Sub-Matrix 29A portion of a matrix can be extracted and stored in asmaller matrix by specifying the names of both matricesand the rows and columns to extract. The syntax is: sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;where r1 and r2 specify the beginning and ending rowsand c1 and c2 specify the beginning and ending columnsto be extracted to make the new matrix.
  29. 29. MATLAB Matrices 30 A column vector can be Here we extract column 2 extracted from a matrix. of the matrix and make a As an example we create a column vector: matrix below:» matrix=[1,2,3;4,5,6;7,8,9] » col_two=matrix( : , 2)matrix = col_two = 1 2 3 4 5 6 2 7 8 9 5 8
  30. 30. MATLAB Matrices 31 A row vector can be Here we extract row 2 of extracted from a matrix. the matrix and make a As an example we create row vector. Note that a matrix below: the 2:2 specifies the second row and the 1:3» matrix=[1,2,3;4,5,6;7,8,9] specifies which columns of the row.matrix = » rowvec=matrix(2 : 2 , 1 : 3) 1 2 3 4 5 6 rowvec = 7 8 9 4 5 6
  31. 31. Topics.. 32What is MATLAB ??Basic Matrix OperationsScript Files /M-files and Function FilesSome more Operations and FunctionsPlotting functions ..
  32. 32. Use of M-File 33There are two kinds of M-files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function. Click to create a new M-File
  33. 33. M-File as script file 34 Save file as filename.m Type what you want to do, eg. Create matrices If you include “;” at the end of each statement, result will not be shown immediatelyRun the file by typing the filename in the command window
  34. 34. MATLAB Function File 35function [a b c] = myfun(x, y) Write these two lines to a file myfun.mb = x * y; a = 100; c = x.^2; and save it on MATLAB’s path>> myfun(2,3) % called with zero outputsans = 100>> u = myfun(2,3) % called with one outputu = 100>> [u v w] = myfun(2,3) % called with all outputsu = 100v = Any return value which is not stored in 6 an output variable is simply discardedw = 4
  35. 35. Topics.. 36What is MATLAB ??Basic Matrix OperationsScript Files and M-filesSome more Operations and FunctionsPlotting functions ..
  36. 36. Some Useful MATLAB commands 37who List known variableswhos List known variables plus their sizehelp >> help sqrt Help on using sqrtlookfor >> lookfor sqrt Search for keyword sqrt in m-fileswhat >> what a: List MATLAB files in a:clear Clear all variables from work spaceclear x y Clear variables x and y from work spaceclc Clear the command window
  37. 37. Some Useful MATLAB commands 38what List all m-files in current directorydir List all files in current directoryls Same as dirtype test Display test.m in command windowdelete test Delete test.mcd a: Change directory to a:chdir a: Same as cdpwd Show current directorywhich test Display directory path to ‘closest’test.m
  38. 38. MATLAB Logical Functions 39 MATLAB also supports some logical functions.xor (exclusive or) Ex: xor (a, b) Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0.any (x) returns 1 if any element of x is nonzeroall (x) returns 1 if all elements of x are nonzeroisnan (x) returns 1 at each NaN in xisinf (x) returns 1 at each infinity in xfinite (x) returns 1 at each finite value in x
  39. 39. Matlab Selection Structures 40An if - elseif - else structure in MATLAB.Note that elseif is one word.if expression1 % is true % execute these commandselseif expression2 % is true % execute these commandselse % the default % execute these commandsend
  40. 40. MATLAB Repetition Structures 41A for loop in MATLAB for x = array for ind = 1:100 b(ind)=sin(ind/10) endwhile loop in MATLAB while expression while x <= 10 % execute these commands end
  41. 41. 42x=0.1:0.1:10;b=sin(x);Plot(b,x)------ nocomputationalcomplexity
  42. 42. Scalar - Matrix Addition 43» a=3;» b=[1, 2, 3;4, 5, 6]b= 1 2 3 4 5 6» c= b+a % Add a to each element of bc= 4 5 6 7 8 9
  43. 43. Scalar - Matrix Subtraction 44» a=3;» b=[1, 2, 3;4, 5, 6]b= 1 2 3 4 5 6» c = b - a %Subtract a from each element of bc= -2 -1 0 1 2 3
  44. 44. Scalar - Matrix Multiplication 45» a=3;» b=[1, 2, 3; 4, 5, 6]b= 1 2 3 4 5 6» c = a * b % Multiply each element of b by ac= 3 6 9 12 15 18
  45. 45. Scalar - Matrix Division 46» a=3;» b=[1, 2, 3; 4, 5, 6]b= 1 2 3 4 5 6» c = b / a % Divide each element of b by ac= 0.3333 0.6667 1.0000 1.3333 1.6667 2.0000
  46. 46. The use of “.” – “Element” Operation 47 Given A:Divide each element of Multiply each Square eachA by 2 element of A by 3 element of A
  47. 47. MATLAB Toolboxes 48MATLAB has a number of add-on software modules, calledtoolbox , that perform more specialized computations. Signal Processing Image Processing Communications System Identification Wavelet Filter Design Control System Fuzzy Logic Robust Control -Analysis and Synthesis LMI Control Model Predictive Control …
  48. 48. MATLAB Demo 49Demonstrations are invaluable since they give an indicationof the MATLAB capabilities.A comprehensive set are available by typing the command>>demo in MATLAB prompt. demo
  49. 49. An Interesting, MATLAB command 50whyIn case you ever needed a reason
  50. 50. Topics.. 51What is MATLAB ??Basic Matrix OperationsScript Files and M-filesSome more Operations and FunctionsPlotting functions ..
  51. 51. Plot 52 ExamplePLOT Linear plot. x = [-3 -2 -1 0 1 2 3]; PLOT(X,Y) plots vector Y y1 = (x.^2) -1; versus vector X plot(x, y1,bo-.); PLOT(Y) plots the columns of Y versus their index PLOT(X,Y,S) with plot symbols and colors See also SEMILOGX, SEMILOGY, TITLE, XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT... 52
  52. 52. Plot Properties 53 ExampleXLABEL X-axis label. ... xlabel(x values); XLABEL(text) adds text ylabel(y values); beside the X-axis on the current axis.YLABEL Y-axis label. YLABEL(text) adds text beside the Y-axis on the current axis. 53
  53. 53. Hold 54 ExampleHOLD Hold current graph. ... hold on; HOLD ON holds the current y2 = x + 2; plot and all axis properties so plot(x, y2, g+:); that subsequent graphing commands add to the existing graph. HOLD OFF returns to the default mode HOLD, by itself, toggles the hold state. 54
  54. 54. Subplot 55SUBPLOT Create axes in tiled positions. SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of small axes Example x = [-3 -2 -1 0 1 2 3]; y1 = (x.^2) -1; % Plot y1 on the top subplot(2,1,1); plot(x, y1,bo-.); xlabel(x values); ylabel(y values); % Plot y2 on the bottom subplot(2,1,2); y2 = x + 2; plot(x, y2, g+:); 55
  55. 55. Figure 56 FIGURE Create figure window. FIGURE, by itself, creates a new figure window, and returns its handle.Examplex = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;% Plot y1 in the 1st Figureplot(x, y1,bo-.);xlabel(x values);ylabel(y values);% Plot y2 in the 2nd Figurefigurey2 = x + 2;plot(x, y2, g+:); 56
  56. 56. Surface Plot 57x = 0:0.1:2;y = 0:0.1:2;[xx, yy] = meshgrid(x,y);zz=sin(xx.^2+yy.^2);surf(xx,yy,zz)xlabel(X axes)ylabel(Y axes) 57
  57. 57. 3 D Surface Plot 58contourf-colorbar-plot3-waterfall-contour3-mesh-surf 58
  58. 58. MATLAB Applications 59 DSP>> t=-2*pi:0.1:2*pi;y=1.5*sin(t);plot(t,y);xlabel(------> time)ylabel(------> sin(t)) 59
  59. 59. MATLAB Applications 60 DSP>> t=-2*pi:0.1:2*pi;y=1.5*cos(t);stem(t,y);xlabel(------> time)ylabel(------> sin(t)) 60
  60. 60. MATLAB Applications 61DSP n=input(enter value of n) t=0:1:n-1; y1=ones(1,n); %unit step y2=[zeros(1,4) ones(1,n-4)]; %delayed unit step subplot(2,1,1); stem(t,y1,filled);ylabel(amplitude); xlabel(n----->);ylabel(amplitude); subplot(2,1,2); stem(t,y2,filled); xlabel(n----->);ylabel(amplitude); 61
  61. 61. MATLAB Applications 62DSP 62
  62. 62. MATLAB Applications 63Control SystemsTransfer Function p1 s n + p 2 s n −1 + ... + p n +1 H (s ) = q1 s m + q1 s m −1 + ... + q m +1 where p1 , p 2 ... p n +1 numerator coefficients q1 , q1 ... q m +1 denominator coefficients 63
  63. 63. MATLAB Applications 64Control SystemsTransfer Function Consider a linear time invariant (LTI) single- input/single-output system y + 6 y + 5 y = 4u + 3u Applying Laplace Transform to both sides with zero initial conditions Y ( s) 4s + 3 G ( s) = = 2 U ( s) s + 6s + 5 64
  64. 64. MATLAB Applications 65Control SystemsTransfer Function>> num = [4 3]; >> [num,den] =>> den = [1 6 5]; tfdata(sys,v)>> sys = tf(num,den) num = Transfer function: 0 4 3 4s+3 den = ----------------- 1 6 5 s^2 + 6 s + 5 65
  65. 65. MATLAB Applications 66Control SystemsZero-pole-gain model (ZPK) (s − p1)(s − p2 ) +... + (s − pn )H (s ) = K (s −q1)(s −q2 ) +... + (s −qm )wherep1 , p2 ... pn+1 the zeros of H(s) q1,q1 ... qm+1 the poles of H(s) 66
  66. 66. MATLAB Applications 67Control SystemsZero-pole-gain model (ZPK) Consider a Linear time invariant (LTI) single- input/single-output system y + 6 y + 5 y = 4u + 3u Applying Laplace Transform to both sides with zero initial conditions Y (s) 4s + 3 4( s + 0.75) G (s) = = 2 = U ( s ) s + 6 s + 5 ( s + 1)( s + 5) 67
  67. 67. MATLAB Applications 68Control Systems >> G=tf([4 3],[1 6 5]) >> [z,p,k]=zpkdata(G) Transfer function: z= 4s+3 [-0.7500] ------------- s^2 + 6 s + 5 p= [-5;-1] k= 4 68
  68. 68. MATLAB Applications 69Control Systems>> bode(G) 69
  69. 69. MATLAB Applications 70Control Systems>> rlocus(G) 70
  70. 70. MATLAB Applications 71Control Systems>> nyquist(G) 71
  71. 71. MATLAB Applications 72Control Systems>> step(G) 72
  72. 72. MATLAB Applications 73Control Systems>> impulse(G) 73
  73. 73. MATLAB Applications 74Communication>> t=0:pi/100:2*pi;>> x=sin(t);>> subplot(211);plot(t,x);>> Fc=1000;>> Fs=2000;>> y=ammod(x,Fc,Fs);>> subplot(212);plot(t,y); 74
  74. 74. MATLAB Applications 75Communication 75
  75. 75. Online MATLAB Resources 76www.mathworks.com/www.mathtools.net/MATLABwww.math.utah.edu/lab/ms/matlab/matlab.htmlweb.mit.edu/afs/athena.mit.edu/software/matlab/ www/home.htmlwww.utexas.edu/its/rc/tutorials/matlab/www.math.ufl.edu/help/matlab-tutorial/www.indiana.edu/~statmath/math/matlab/links.htmlwww-h.eng.cam.ac.uk/help/tpl/programs/matlab.html 76
  76. 76. Reference Books 77Mastering MATLAB 7, D. Hanselman and B. Littlefield,Prentice Hall, 2004Getting Started with MATLAB 7: A Quick Introductionfor Scientists and Engineers, R. Pratap, Oxford UniversityPress, 2005. 77
  77. 77. Some More Web Resources 78 MATLAB Educational sites:http://www.eece.maine.edu/mm/matweb.html Yahoo! MATLAB Web site:dir.yahoo.com/Science/mathematics/software/matlab/ Newsgroup: comp.soft-sys.matlab 78
  78. 78. Thanks 79Questions ??

×