480 likes | 495 Views
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
E N D
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
The Command Window and History We will use this matrix, called A, in many examples.
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
The Workspace Browser • The workspace holds the arrays currently accessible in the development environment • You can import new data or delete existing data
The Array Editor • Double clicking an array in the workspace opens up the array editor • You can examine or edit the contents
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
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
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?
Expressions and Functions • Expressions and functions obey algebraic rulesz = sqrt(besselk(4/3,rho-i))z = 0.3730+ 0.3214i • Some important constant functions
Generating Matrices randn produces normally distributed random numbers
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
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
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 ¼
Array Operations • For example, to square the elements of A, enter the expression A.*A
Building Tables • An example • Let n = (0:9)’ • Let pows = [n n.^2 2.^n] • Another example
A Preview of Statistics • Let the columns represent heart rate, weight and hours of exercise per week
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
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
The if command • An example • Some useful boolean tests Useful Boolean tests for matrices
The switch command • Note: the break command in C++ is not required in matlab (yeah !!)
Commands for repetition • The for command (notice the required ‘end’) • The while command (also requires ‘end’) Does anyone recognize what this code fragment does?
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?
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
Dynamic Structures • Matlab supports heterogeneous structures • Unlike Java, C++, Pascal … fields are dynamic
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
Functions in matlab • Built-in functions • Found in toolbox/matlab/matfun • An example, the function rank
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
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
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
Function Example - 1 1 3 2
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
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
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);
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
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));
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