Matlab tutorial


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Matlab tutorial

  1. 1. Eng. 8054 Advanced Marine Vehicles <ul><ul><li>Todays agenda: </li></ul></ul><ul><ul><li>Lab tomorrow at 2pm (structures lab)‏ </li></ul></ul><ul><ul><li>Advanced Marine Party </li></ul></ul><ul><ul><li>Introduction to Matlab </li></ul></ul>
  2. 2. Eng. 8054 Advanced Marine Vehicles <ul><ul><li>Introduction to Matlab </li></ul></ul>
  3. 3. What is Matlab ? Matlab is a commercial &quot;Matrix Laboratory&quot; package which operates as an interactive programming environment. Matlab is available for PC's, Macintosh and UNIX systems. Matlab is well adapted to numerical experiments. Matlab program and script files ( m-files ) always have filenames ending with &quot;.m&quot;; The programming language is exceptionally straightforward since almost every data object is assumed to be an array. Graphical output ( figure ) is available to supplement numerical results. Online help is available from the Matlab prompt (a double arrow) by typing help .
  4. 4. What kind of graphics are possible in Matlab ? Polar plot: t=0:.01:2*pi; polar(t,abs(sin(2*t).*cos(2*t))); Line plot: x=0:0.05:5;,y=sin(x.^2);,plot(x,y); Stem plot: x = 0:0.1:4;, y = sin(x.^2).*exp(-x); stem(x,y)
  5. 5. What kind of graphics is possible in Matlab ? Mesh plot: z=peaks(25);, mesh(z); Surface plot: z=peaks(25);, surf(z);, colormap(jet); Contour plot: z=peaks(25);,contour(z,16); Quiver plot:
  6. 6. Using Help in Matlab Online help is available from the Matlab prompt ( >> a double arrow), both generally (listing of all available commands): >> help [a long list of help topics follows] and for specific commands: >> help fft [a help message on the fft function follows].
  7. 7. What is Matlab ? <ul><li>MATLAB consists of: </li></ul><ul><li>The MATLAB language </li></ul><ul><li>a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. </li></ul><ul><li>The MATLAB working environment </li></ul><ul><li>the set of tools and facilities that you work with as the MATLAB user or programmer, including tools for developing, managing, debugging, and profiling </li></ul><ul><li>Handle Graphics </li></ul><ul><li>the MATLAB graphics system. It includes high-level commands for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. </li></ul><ul><li>… (cont’d)‏ </li></ul>
  8. 8. What is Matlab ? <ul><li>The MATLAB function library. </li></ul><ul><li>a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms as well as special image processing related functions </li></ul><ul><li>The MATLAB Application Program Interface (API)‏ </li></ul><ul><li>a library that allows you to write C and Fortran programs that interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files. </li></ul>
  9. 9. What is Matlab ? <ul><li>Some facts for a first impression </li></ul><ul><li>Everything in MATLAB is a matrix ! </li></ul><ul><li>MATLAB is an interpreted language, no compilation needed (but possible)‏ </li></ul><ul><li>MATLAB does not need any variable declarations, no dimension statements, has no packaging, no storage allocation, no pointers </li></ul><ul><li>Programs can be run step by step, with full access to all variables, functions etc. </li></ul>
  10. 10. What does matlab code look like? <ul><li>t = 0:pi/100:2*pi; </li></ul><ul><li>y = sin(t); </li></ul><ul><li>plot(t,y)‏ </li></ul>
  11. 11. What does matlab code look like? Remember: EVERYTHING IN MATLAB IS A MATRIX ! creates 1 x 200 Matrix Argument and result: 1 x 200 Matrix <ul><li>t = 0:pi/100:2*pi; </li></ul><ul><li>y = sin(t); </li></ul><ul><li>plot(t,y)‏ </li></ul>
  12. 13. <ul><li>Rows and columns are always numbered starting at 1 </li></ul><ul><li>A single number is really a 1 x 1 matrix in Matlab! </li></ul><ul><li>Matlab variables are not given a type, and do not need to be declared </li></ul><ul><li>Any matrix can be assigned to any variable </li></ul>
  13. 14. Building matrices with [ ]: A = [2 7 4] A = [2; 7; 4] A = [2 7 4; 3 8 9] B = [ A A ] 2 7 4 2 7 4 2 7 4 3 8 9 2 7 4 3 8 9 2 7 4 3 8 9
  14. 16. <ul><li>A matrix can be indexed using another matrix, to produce a subset of its elements: </li></ul><ul><li>a = [100 200 300 400 500 600 700] b = [3 5 6] </li></ul><ul><li>c = a(b): </li></ul><ul><li>300 500 600 </li></ul>
  15. 17. Matrices <ul><li>a vector x = [1 2 5 1] </li></ul><ul><li>x = </li></ul><ul><li>1 2 5 1 </li></ul><ul><li>a matrix x = [1 2 3; 5 1 4; 3 2 -1] </li></ul><ul><li>x = </li></ul><ul><li>1 2 3 </li></ul><ul><li>5 1 4 </li></ul><ul><li>3 2 -1 </li></ul>
  16. 18. Matrices <ul><li>x(i,j) subscription </li></ul><ul><li>whole row </li></ul><ul><li>whole column </li></ul>y=x(2,3)‏ y = 4 y=x(3,:)‏ y = 3 2 -1 y=x(:,2)‏ y = 2 1 2
  17. 19. Operators (arithmetic)‏ <ul><li>+ addition </li></ul><ul><li>- subtraction </li></ul><ul><li>* multiplication </li></ul><ul><li>/ division </li></ul><ul><li>^ power </li></ul><ul><li>‘ complex conjugate transpose </li></ul>.* element-by-element mult ./ element-by-element div .^ element-by-element power .‘ transpose
  18. 20. Operators (relational, logical) <ul><li>== equal </li></ul><ul><li>~= not equal </li></ul><ul><li>< less than </li></ul><ul><li><= less than or equal </li></ul><ul><li>> greater than </li></ul><ul><li>>= greater than or equal </li></ul><ul><li>& AND </li></ul><ul><li>| OR </li></ul><ul><li>~ NOT </li></ul>pi 3.14159265… j imaginary unit, i same as j
  19. 21. Generating Vectors from functions <ul><li>zeros(M,N) MxN matrix of zeros </li></ul><ul><li>ones(M,N) MxN matrix of ones </li></ul><ul><li>rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1)‏ </li></ul><ul><li>x = zeros(1,3)‏ </li></ul><ul><li>x = </li></ul><ul><li>0 0 0 </li></ul><ul><li>x = ones(1,3)‏ </li></ul><ul><li>x = </li></ul><ul><li>1 1 1 </li></ul><ul><li>x = rand(1,3)‏ </li></ul><ul><li>x = </li></ul><ul><li>0.9501 0.2311 0.6068 </li></ul>
  20. 22. Programming in Matlab (M-files)‏ <ul><li>Executing commands in the command window is fine for short scripts; but when dealing with long scripts for complex problem-solving (or when programming) M-files is a must. </li></ul><ul><li>It allows the user to write MATLAB command in a text file (called M-file) and then MATLAB will open the file and execute the commands exactly as it would if the user typed them at the MATLAB Command Window. The M-file editor is the MATLAB’s tool for creating M-files. </li></ul>
  21. 23. Programming in Matlab (M-files)‏ <ul><li>There are two basic kinds of m-files: </li></ul><ul><ul><li>Scripts </li></ul></ul><ul><ul><li>Functions </li></ul></ul><ul><li>Scripts are m-files that execute a series of statements </li></ul><ul><li>Functions are m-files that accept arguments and produce an output </li></ul>
  22. 24. Example Script 1 <ul><li>Find the solution, x, to the following system of equations </li></ul>
  23. 25. Example Script 1: solution <ul><li>Use the MATLAB editor to create a new file </li></ul><ul><li>Enter the following statement: </li></ul><ul><li>A = [1 2 3; 3 3 4; 2 3 3]; </li></ul><ul><li>b = [1; 1; 2]; </li></ul><ul><li>x = A </li></ul>
  24. 26. Example Script 2 <ul><li>Plot the following cosine functions, </li></ul><ul><li>y1 = 2 cos(x), </li></ul><ul><li>y2 = cos(x) </li></ul><ul><li>y3 = 0.5cos(x)‏ </li></ul><ul><li>in the interval: </li></ul>
  25. 27. Example Script 1: solution <ul><li>Use the MATLAB editor to create a new file </li></ul><ul><li>Enter the following statement: </li></ul><ul><li>x = 0:pi/100:2*pi; </li></ul><ul><li>y1 = 2*cos(x); </li></ul><ul><li>y2 = cos(x); </li></ul><ul><li>y3 = 0.5*cos(x); </li></ul><ul><li>plot(x,y1,'--',x,y2,'-',x,y3,':')‏ </li></ul><ul><li>xlabel('0 leq x leq 2pi')‏ </li></ul><ul><li>ylabel('Cosine functions')‏ </li></ul><ul><li>legend('2*cos(x)','cos(x)','0.5*cos(x)')‏ </li></ul><ul><li>title('Typical example of multiple plots')‏ </li></ul><ul><li>axis([0 2*pi -3 3])‏ </li></ul>
  26. 28. Script shortcomings <ul><li>All variables created in a script file are added to the workspace. This may be undesirable because: </li></ul><ul><ul><li>Variables already existing in the workspace may be overwritten. </li></ul></ul><ul><ul><li>The execution of the script can be affected by the state variables in the workspace. </li></ul></ul><ul><li>Use a function for anything complicated </li></ul>
  27. 29. The Anatomy of a Function <ul><li>function f = factorial(n) (1)‏ </li></ul><ul><li>% FACTORIAL(N) returns the factorial of N. (2)‏ </li></ul><ul><li>% Compute a factorial value. (3)‏ </li></ul><ul><li>f = prod(1:n); (4)‏ </li></ul>
  28. 30. Differences between Scripts and Functions
  29. 31. Functions: input & output arguments <ul><li>input arguments are listed inside parentheses following the function name. </li></ul><ul><li>The output arguments are listed inside the brackets on the left side. They are used to transfer the output from the function file. </li></ul><ul><li>The general form looks like this </li></ul><ul><li>function [outputs] = function_name(inputs)‏ </li></ul>
  30. 32. Functions: input & output arguments <ul><li>Examples of input and output arguments </li></ul><ul><li>function area=TrapArea(a,b,h) Three inputs and one output </li></ul><ul><li>function [h,d]=motion(v,angle) Two inputs and two outputs </li></ul>
  31. 33. Inputs to scripts? <ul><li>Inputs are sent to script files by: </li></ul><ul><li>Defining the variable in the script itself </li></ul><ul><li>Defining the variable in the workspace </li></ul><ul><li>Defining the variable when the script executes </li></ul>
  32. 34. Inputs to scripts? <ul><li>We've discussed the first two, so lets look at </li></ul><ul><li>Defining the variable when the script executes </li></ul><ul><li>This means that we will ask the user to supply some information when the script is executed </li></ul><ul><ul><li>Using the input command </li></ul></ul>
  33. 35. The Input Command <ul><li>Lets try an example script </li></ul><ul><li>% This script file calculates the average of points </li></ul><ul><li>% scored in three games. </li></ul><ul><li>% The point from each game are assigned to a variable </li></ul><ul><li>% by using the `input' command. </li></ul><ul><li>game1 = input('Enter the points scored in the first game '); </li></ul><ul><li>game2 = input('Enter the points scored in the second game '); </li></ul><ul><li>game3 = input('Enter the points scored in the third game '); </li></ul><ul><li>average = (game1+game2+game3)/3 </li></ul>
  34. 36. Flow Control <ul><li>The most common decision-making (or flow control) structures in matlab are: </li></ul><ul><li>The if ... else ... end structure </li></ul><ul><li>Example, based on quadratic formula: </li></ul><ul><li>discr = b*b - 4*a*c; </li></ul><ul><li>if discr < 0 </li></ul><ul><ul><li>disp('Warning: discriminant is negative, roots are imaginary'); </li></ul></ul><ul><li>elseif discr == 0 </li></ul><ul><ul><li>disp('Discriminant is zero, roots are repeated')‏ </li></ul></ul><ul><li>else </li></ul><ul><ul><li>disp('Roots are real')‏ </li></ul></ul><ul><li>end </li></ul>
  35. 37. Flow Control <ul><li>Logical operators are used to compare two objects: </li></ul>
  36. 38. Flow Control <ul><li>Another common flow control structure is: </li></ul><ul><li>The for ... end loop </li></ul><ul><li>Example: </li></ul><ul><li>for ii=1:5 </li></ul><ul><ul><li>x=ii*ii </li></ul></ul><ul><li>end </li></ul>
  37. 39. Flow Control <ul><li>Can also use nested loops as well. </li></ul><ul><li>To populate a 5x5 symmetric matrix where the indices correspond to i/j we have: </li></ul><ul><li>n = 5; A = eye(n); </li></ul><ul><li>for j=2:n </li></ul><ul><ul><li>for i=1:j-1 </li></ul></ul><ul><ul><ul><li>A(i,j)=i/j; </li></ul></ul></ul><ul><ul><ul><li>A(j,i)=i/j; </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>end </li></ul>
  38. 40. Saving output to a file <ul><li>The command fprintf is used to write output to a file. </li></ul><ul><li>To save the results of some computation to a file in a text format requires the following </li></ul><ul><li>steps: </li></ul><ul><li>1. Open a file using fopen </li></ul><ul><li>2. Write the output using fprintf </li></ul><ul><li>3. Close the file using fclose </li></ul>
  39. 41. Saving output to a file <ul><li>% write some variable length strings to a file: </li></ul><ul><li>op = fopen('weekdays.txt','wt'); </li></ul><ul><li>fprintf(op,'Sunday Monday Tuesday Wednesday '); </li></ul><ul><li>fprintf(op,'Thursday Friday Saturday '); </li></ul><ul><li>fclose(op); </li></ul><ul><li>Notes: </li></ul><ul><li>the option 'wt' is used in the windows platform to set a file for writing. </li></ul><ul><li>the command forces a carriage return </li></ul>
  40. 42. Furthering your matlab skills <ul><li>The scripts presented in this lecture are merely an introduction to matlab that barely scrape the surface </li></ul><ul><li>To understand it yourself you must really get your hands dirty and dig into programming. </li></ul><ul><li>The built-in help is very good in matlab, so if you are unsure of how to do something you should check there first </li></ul>