1 / 48

An Introduction to Matlab

An Introduction to Matlab. This introduction will be a PowerPoint presentation followed by a demonstration of Matlab The major topics will include The development environment Manipulating matrices Generating graphics Writing programs Feel free to ask questions at any time

alvinjones
Download Presentation

An Introduction to Matlab

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. An Introduction to Matlab • This introduction will be a PowerPoint presentation followed by a demonstration of Matlab • The major topics will include • The development environment • Manipulating matrices • Generating graphics • Writing programs • Feel free to ask questions at any time • When I can’t answer the question, I will refer it to our local expert, Rahman Tashakkori

  2. The Matlab Desktop

  3. The Command Window and History We will use this matrix, called A, in many examples.

  4. The HelpSystem

  5. The Current Directory Browser • The current directory in the toolbar shows the files shown below • The search path can be changed by selecting File -> Set path

  6. The Workspace Browser • The workspace holds the arrays currently accessible in the development environment • You can import new data or delete existing data

  7. The Array Editor • Double clicking an array in the workspace opens up the array editor • You can examine or edit the contents

  8. The Editor/Debugger

  9. Entering and Generating Matrices • Direct assignment in row major order, such asA = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] (note: this is our “magic square” example) • Import matrices from external files • Generate matrices from built-in functions • sum(A) returns the sum of all the columns, which is 34 for each column • sum(A′)′ returns the sum for all row, which is 34, note that the transpose operation is ′ • sum(diag(A)) sums the main diagonal, also 34 • sum(diag(fliplr(A))) sums the diagonal from lower left to upper right, it is also 34 • Create matrices with your own functions in M-files

  10. Accessing Matrix Elements • Subscripts • Uses parentheses to indicate subscripts • A(1,4) + A(2,4) + A(3,4) + A(4,4) returns 34 • Out of range indices • Trying to read an element out of range produces an error message • Trying to assign a value to an element out of range expands the matrix !!A(5,4) = 17 produces 16 3 2 13 0 5 10 11 8 0 9 6 7 12 0 4 15 14 1 17

  11. The Colon Operator • Examples • 1:5 produces 1 2 3 4 5 • 20:-3:0 produces 20 17 14 11 8 5 2 • 0:pi/4:pi produces 0 0.7854 1.5708 2.3562 3.1416 • Accessing portions of a matrix • A(1:k,j) references the first k elements in the j column • A(:,end) references all elements in the last column • How could you reference all elements in the last row?

  12. Expressions and Functions • Expressions and functions obey algebraic rulesz = sqrt(besselk(4/3,rho-i))z = 0.3730+ 0.3214i • Some important constant functions

  13. Generating Matrices randn produces normally distributed random numbers

  14. Various Matrix Operations - 1 • Concatenation, using our magic square A • This isn’t quite a magic square but the columns add up to the same value

  15. Various Matrix Operations - 2 • Deleting rows and columns • A(: , 2) = [ ] removes the second column • How would you remove the last row? • Single elements can only be removed from vectors • Some operations with transpose • If you tried to apply the determinant operation, you would find det(A) = 0, so this matrix is not invertible; if you tried inv(A) you would get an error

  16. Various Matrix Operations - 3 • The eigenvalue contains a 0, indicating singularity • P = A/34 is doubly stochastic, as shown above • P^5 (raised to the fifth power) converges towards ¼, as k in p^k gets larger the values approach ¼

  17. Various Matrix Operations - 4

  18. Array Operations • For example, to square the elements of A, enter the expression A.*A

  19. Building Tables • An example • Let n = (0:9)’ • Let pows = [n n.^2 2.^n] • Another example

  20. A Preview of Statistics • Let the columns represent heart rate, weight and hours of exercise per week

  21. Example of Simple Plotting

  22. An Example - 1 x = -1:.1:1; % Define the range of x y = x.^3; % Raise each element in x to the third power plottools

  23. An Example - 2

  24. An Example - 3

  25. An Example - 4

  26. An Example - 5

  27. An Example - 6

  28. Programming in Matlab • Control structures • Selection (if and switch) • Repetition (for, while, break, continue) • Other (try … catch, return) • Dynamic Structures • Scripts and M files • User defined functions • Two examples • Finding the periodicity of sunspots • Multiplying polynomials using FFT

  29. The if command • An example • Some useful boolean tests Useful Boolean tests for matrices

  30. The switch command • Note: the break command in C++ is not required in matlab (yeah !!)

  31. Commands for repetition • The for command (notice the required ‘end’) • The while command (also requires ‘end’) Does anyone recognize what this code fragment does?

  32. Continue and Break • The continue command What does this code fragment do? • The break command Here is the finding the solution of a polynomial using bisection; why is the ‘break’ command an improvement?

  33. try … catch and return • Exception handling You can examine the error using lasterr An error in the exception handler causes the program to terminate • The return command • Terminates execution • If inside a user defined function, returns to the calling environment • Otherwise returns to keyboard input

  34. Dynamic Structures • Matlab supports heterogeneous structures • Unlike Java, C++, Pascal … fields are dynamic

  35. Scripts and M files • An M file (.m extension) stores matlab code • The file name is used to reference the code • The code is a sequence of commands that is executed • An example Stored in magicrank.m Executed by ‘magicrank’on command line

  36. Functions in matlab • Built-in functions • Found in toolbox/matlab/matfun • An example, the function rank

  37. Other Types of Functions • Anonymous functions (shades of Lisp!) • Syntax : f = @(arglist)expression • sqr = @(x) x.^2;a = sqr(5)a = 25 • Characteristics of named functions • Primary functions are stored in m files • Secondary functions called by the primary function may be stored in the same m file • Functions may be nested • Functions with different inputs may be overloaded • Functions can accept input, return output, and have local variables; scripts cannot do any of these things

  38. Function Details - 1 • Functions can reference GLOBAL variables • Other syntax issues • String arguments may quoted (single quotes) or unquoted, but if a return value is expected, you must use quotes • An example of constructing string arguments

  39. Function Details - 2 • The eval function (shades of Lisp again!) • Passed a string argument • Matlab executes the statement or evaluates the expression in the string • Function handles • Example, a handler for the sin functionfhandle = @sin;function x = plot_fhandle(fhandle, data)plot(data, fhandle(data)) • Function handles are useful for passing function arguments to other functions

  40. Function Example - 1 1 3 2

  41. Function Example - 2 Find a minimum near 0.5 Evaluate the function at this minimum Quadrature performs numerical approx. of definite integrals (i.e. area under the curve) There is no zero between 0 and 0.5

  42. Sunspot data has been collected since the 1700s; sample data is shown to the right Our program should perform several tasks Read and store the data in two arrays Plot the raw data Apply fast Fourier transform to find the frequency spectrum Find the frequency and then the period as its inverse Plot the periods Find the maximum period (slightly over 11 years) 1700 5.0 1701 11.0 1702 16.0 1703 23.0 1704 36.0 1705 58.0 1706 29.0 1707 20.0 1708 10.0 1709 8.0 1710 3.0 1711 0.0 1712 0.0 1713 2.0 1714 11.0 1715 27.0 1716 47.0 Sunspots - 1

  43. Sunspots - 2 function cycle = sunspotdemo() % the sunspot program is a demo from matlab % this has been changed into a function by % Barry L. Kurtz load sunspot.dat year=sunspot(:,1); wolfer=sunspot(:,2); plot(year,wolfer) Y=fft(wolfer); N=length(Y); Y(1)=[]; power=abs(Y(1:N/2)).^2; nyquist=1/2; freq=(1:N/2)/(N/2)*nyquist; period=1./freq; pause; plot(period,power),axis([0 40 0 2e7]), grid on [mp,index]=max(power); pause; cycle=period(index);

  44. Sunspot - 3

  45. Sunspot - 4

  46. Multiplying Polynomials Using FFT • The general strategy • Things to note • we need to double the degree bound before evaluating • to find values at new points we must use the coefficient representation

  47. Matlab code to multiply polynomials function c_coef = poly_mult(a_coef,b_coef) % poly_mult inputs the coefficients of two polynomial, % entered from most significant to least significant, % and returns the coefficients of the product polynomial % poly_mult([1,2],[1,3]) returns 0 1 5 6 % written by Barry L. Kurtz extend_a_coef = [fliplr(a_coef), zeros(1,length(a_coef))]; extend_b_coef = [fliplr(b_coef), zeros(1,length(b_coef))]; ffta=fft(extend_a_coef); fftb=fft(extend_b_coef); fftc=ffta.*fftb; c_coef=fliplr(ifft(fftc));

  48. Testing Polynomial Multiplication >> poly_mult([1,2],[1,3]) ans = 0 1 5 6 >> poly_mult([1 2 3],[1 2 3]) ans = 0 1 4 10 12 9 >> poly_mult([2],[3]) ans = 0 6 >> poly_mult([3 0 0],[0 2 0]) ans = 0 0 6 0 0 0

More Related