Professional Documents
Culture Documents
Intro MATLAB
2
Table of Contents Day One Overview Basic Interfaces Arrays, Matrices, Operators Programming Data I/O
Intro MATLAB
4
Basic Data Analysis Numerical Analysis Graphics, Data Visualization, Movies Inter-language Programming
Intro MATLAB
5
Overview
MATLAB
MATrix LABoratory Powerful, extensible, highly integrated computation, programming, visualization, and simulation package Widely used in engineering, mathematics, and science Why?
Intro MATLAB
7
MATLABs Appeal
Interactive code development proceeds incrementally; excellent development and rapid prototyping environment Basic data element is the auto-indexed array This allows quick solutions to problems that can be formulated in vector or matrix form Powerful GUI tools Large collection of toolboxes: collections of topicrelated MATLAB functions that extend the core functionality significantly
Intro MATLAB
8
MATLAB Toolboxes
Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object
Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design
Control Design Control System Fuzzy Logic Robust Control -Analysis and Synthesis Model Predictive Control
Intro MATLAB
9
Intro MATLAB
10
MATLAB System
Language: arrays and matrices, control flow, I/O, data structures, user-defined functions and scripts Working Environment: editing, variable management, importing and exporting data, debugging, profiling Graphics system: 2D and 3D data visualization, animation and custom GUI development Mathematical Functions: basic (sum, sin,) to advanced (fft, inv, Bessel functions, ) API: can use MATLAB with C, Fortran, and Java, in either direction
Intro MATLAB
11
Intro MATLAB
12
References
Mastering MATLAB 7, D. Hanselman and B. Littlefield, Prentice Hall, 2004 Getting Started with MATLAB 7: A Quick Introduction for Scientists and Engineers, R. Pratap, Oxford University Press, 2005.
Intro MATLAB
13
Basic Interfaces
15
Intro MATLAB
16
Intro MATLAB
18
Intro MATLAB
19
matlab\general matlab\ops matlab\lang matlab\elmat matlab\elfun matlab\specfun matlab\matfun matlab\datafun matlab\polyfun matlab\funfun matlab\sparfun matlab\scribe matlab\graph2d matlab\graph3d matlab\specgraph matlab\graphics etc...
General purpose commands. Operators and special characters. Programming language constructs. Elementary matrices and matrix manipulation. Elementary math functions. Specialized math functions. Matrix functions - numerical linear algebra. Data analysis and Fourier transforms. Interpolation and polynomials. Function functions and ODE solvers. Sparse matrices. Annotation and Plot Editing. Two dimensional graphs. Three dimensional graphs. Specialized graphs. Handle Graphics.
Intro MATLAB
20
- Matrix or vector norm. - Estimate the matrix 2-norm. - Matrix rank. - Determinant. - Sum of diagonal elements. - Null space. - Orthogonalization. - Reduced row echelon form. - Angle between two subspaces.
Intro MATLAB
21
Intro MATLAB
22
Bytes 8 8 8
Attributes
Intro MATLAB
23
startup.m
Customize MATLABs start-up behavior Create startup.m file and place in:
My startup.m file:
addpath e:\download\MatlabMPI\src addpath e:\download\MatlabMPI\examples addpath .\MatMPI format short g format compact
Intro MATLAB
24
25
Variable Basics
>> 16 + 24 ans = 40 >> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product product = 8883.8
no declarations needed
Intro MATLAB
26
Variable Basics
>> 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 to Your variables are: comp_sum product show_i retain/restore workspace variables >> product product = 54 >> show_i use home to clear screen and put show_i = cursor at the top of the screen -1
Intro MATLAB
27
MATLAB Data
The basic data type used in MATLAB is the double precision array
No declarations needed: MATLAB automatically allocates required memory Resize arrays dynamically To reuse a variable name, simply use it in the left hand side of an assignment statement MATLAB displays results in scientific notation o Use File/Preferences and/or format function to change default o short (5 digits), long (16 digits) o format short g; format compact (my preference)
Intro MATLAB
28
Variables Revisited
Variable names are case sensitive and over-written when re-used Basic variable class: Auto-Indexed Array Allows use of entire arrays (scalar, 1-D, 2-D, etc) as operands Vectorization: Always use array operands to get best performance (see next slide)
Special variables/functions: ans, pi, eps, inf, NaN, i, nargin, nargout, varargin, varargout, ... Commands who (terse output) and whos (verbose output) show variables in Workspace
Intro MATLAB
29
Vectorization Example*
>> type slow.m tic; x=0.1; for k=1:199901 y(k)=besselj(3,x) + log(x); x=x+0.001; end toc; >> slow Elapsed time is 17.092999 seconds. *times measured on a laptop >> type fast.m tic; x=0.1:0.001:200; y=besselj(3,x) + log(x); toc; >> fast Elapsed time is 0.551970 seconds.
Intro MATLAB
30
Interestingly, Durer also dated this engraving by placing 15 and 14 side-by-side in the magic square.
Intro MATLAB
31
Intro MATLAB
32
Easier Way...
durerBy4 = 16 3 5 10 9 6 4 15 2 11 7 14 13 8 12 1
Intro MATLAB
33
Multidimensional Arrays
>> r = randn(2,3,4) % create a 3 dimensional array filled with normally distributed random numbers r(:,:,1) = -0.6918 0.8580 r(:,:,2) = -0.3999 0.6900 r(:,:,3) = 1.1908 -1.2025 r(:,:,4) = -1.0565 1.4151 -0.8051 0.5287 0.2193 -0.9219 -0.0198 -0.1567 -1.6041 0.2573 0.8156 0.7119 1.2902 0.6686 1.2540 -1.5937 -1.4410 0.5711
% sign precedes comments, MATLAB ignores the rest of the line randn(2,3,4): 3 dimensions, filled with normally distributed random numbers
Intro MATLAB
34
Character Strings
>> hi = ' hello'; >> class = 'MATLAB'; >> hi hi = hello >> class class = MATLAB >> greetings = [hi class] greetings = helloMATLAB >> vgreetings = [hi;class] vgreetings = hello MATLAB
Intro MATLAB
35
Intro MATLAB
36
String Functions
yo = Hello Class >> ischar(yo) ans = 1 >> strcmp(yo,yo) ans = 1
returns 1 if string arguments are the same and 0 otherwise; strcmpi ignores case
Intro MATLAB
37
Set Functions
Arrays are ordered sets:
>> a = [1 2 3 4 5] a = 1 b = 3 4 5 6 7 2 3 4 5 >> b = [3 4 5 6 7]
returns true (1) if arrays are the same size and have the same values returns 1 where a is in b and 0 otherwise
Intro MATLAB
38
Matrix Operations
>> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] durer = 16 5 9 4 MATLAB also has magic(N) (N > 2) function
3 10 6 15
2 11 7 14
13 8 12 1
>> % durer's matrix is "magic" in that all rows, columns, >> % and main diagonals sum to the same number >> column_sum = sum(durer) % MATLAB operates column-wise column_sum = 34 34
34
34
Intro MATLAB
39
Transpose Operator
>> % to get the row sums, we'll use the transpose operator >> % (an apostrophe) >> durer' ans = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Intro MATLAB
40
Diagonal Elements
>> durer durer = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1
>> diag(durer) % diag plucks out the diagonal elements ans = 16 10 7 1 >> sum(diag(durer)) ans = 34
Intro MATLAB
41
Intro MATLAB
42
Matrix Subscripting
>> durer durer = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1
>> diag_sum = durer(1,1) + durer(2,2) + durer(3,3) diag_sum = 33 >> durer(4,4) = pi durer = 16.0000 5.0000 9.0000 4.0000 3.0000 10.0000 6.0000 15.0000 2.0000 11.0000 7.0000 14.0000 13.0000 8.0000 12.0000 3.1416
>> durer(4,4) = 1
Intro MATLAB
43
>> 1:0.9:6 % you can vary the increment (0.9 in this case) ans = 1.0000 1.9000 2.8000 3.7000 4.6000 5.5000
The last element is always less than or equal to the upper limit
Intro MATLAB
44
>> sum(durer(:,end)) % a lone colon is ALL % elements, end is % the last element ans = 34
Intro MATLAB
45
5 9 34
6 8 78
Both operators work with matrices (of course). More later on what is actually calculated Comparison of the use of / and \ on next slide
Intro MATLAB
49
Intro MATLAB
50
Intro MATLAB
51
Line color, style, marker type, all within single quotes; type >> doc LineSpec for all available line properties
Intro MATLAB
52
Lab 1
Create a row vector called X whose elements are the integers 1 through 9. Create another row vector called Temp whose elements are: 15.6 17.5 36.6 43.8 58.2 61.6 64.2 70.4 98.8 These data are the result of an experiment on heat conduction through an iron bar. The array X contains positions on the bar where temperature measurements were made. The array Temp contains the corresponding temperatures. Make a 2-D plot with temperature on the y-axis and position on the x-axis. The data shown in your plot should lie along a straight line (according to physics) but dont because of measurement errors. Use the MATLAB polyfit function to fit the best line to the data (use >> hold on; for multiple plots in same figure). In other words use polyfit to determine the coefficients a and b of the equation T = ax + b Lastly, we can calculate a parameter called chi-square (2) that is a measure of how well the data fits the line. Calculate chi-square by running the MATLAB command that does the following matrix multiplication: >> (Temp-b-a*X)*(Temp-b-a*X)'
Intro MATLAB
53
Lab 2
Write a MATLAB command that will generate a column vector called theta. theta should have values from 2 to 2 in steps of /100. Generate a matrix F that contains values of the following functions in the columns indicated: Column 1: cos() Column 2: cos(2)(1 + sin(2) Column 3: e -0.1|| Evaluate each of the above functions for the values in the theta vector from above. Plot each of the columns of F against theta. Overlay the three plots, using a different color for each. Create a new column vector called maxVect that contains the largest of the three functions above for each theta. Plot maxVect against theta. Create a column vector called maxIndex that has the column number of the maximum value in that row.
Intro MATLAB
54
Programming
55
Outline
MATLAB m-file Editor icon or enter edit command in To start: click Command Window, e.g., >> edit test.m Scripts and Functions Decision Making/Looping if/else switch for and while Running Operating System Commands
Intro MATLAB
56
You can save and run the file/function/script in one step by clicking here
Tip: semi-colons suppress printing, commas (and semicolons) allow multiple commands on one line, and 3 dots () allow continuation of lines without execution
Intro MATLAB
57
Intro MATLAB
58
>> myfun(2,3) % called with zero outputs ans = 100 >> u = myfun(2,3) % called with one output u = 100 >> [u v w] = myfun(2,3) % called with all outputs u = 100 v = Any return value which is not stored in 6 an output variable is simply discarded w = 4
Intro MATLAB
59
Used in scatter pattern analysis: Position of debris resulting from an explosion Establish properties of the explosion: its original location, strength, parts specifications,
Intro MATLAB
60
Interactive Session
>> x = randn(1,12); % generates 12 normally distributed numbers >> y = randn(1,12); >> z = zeros(1,12); % trimesh (used below) needs three arguments >> plot(x,y,'o'); >> tri = delaunay(x,y); >> hold on, trimesh(tri,x,y,z), hold off; % plot triangles >> hidden off %reveal all hidden points >> title(deLaunay Triangulation')
Intro MATLAB
61
Intro MATLAB
62
Intro MATLAB
63
Intro MATLAB
64
Function: Body
anorm = norm(a); bnorm = norm(b); cnorm = norm(c); ab = dot(a,b); bc = dot(b,c); ac = dot(a,c); cosy_ab = ab/(anorm*bnorm); % Calculate cosine of cosy_bc = bc/(bnorm*cnorm); % included angles cosy_ac = ac/(anorm*cnorm); angles(1) = convert2deg(acos(cosy_ab)); % Create output angles(2) = convert2deg(acos(cosy_bc)); angles(3) = convert2deg(acos(cosy_ac)); return % Calculate Dot Products % Local Variables % Calculate vector lengths
Intro MATLAB
65
Intro MATLAB
66
Intro MATLAB
67
Intro MATLAB
68
Intro MATLAB
70
Intro MATLAB
72
if/elseif/else Statement
>> A = 2; B = 3; >> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') end ans = B is bigger
Intro MATLAB
73
switch Statement
>> n = 8 n = 8 >> switch(rem(n,3)) case 0 m = 'no remainder' case 1 m = the remainder is one' case 2 m = the remainder is two' otherwise error('not possible') end m = the remainder is two
Intro MATLAB
74
for Loop
>> for i = 2:5 for j = 3:6 a(i,j) = (i + j)^2 end end >> a a = 0 0 0 0 0 0 0 0 0 0 0 25 36 49 64 0 36 49 64 81 0 49 64 81 100 0 64 81 100 121
Intro MATLAB
75
while Loop
>> b = 4; a = 2.1; count = 0; >> while b - a > 0.01 a = a + 0.001; count = count + 1; end >> count count = 1891
Intro MATLAB
76
A Performance Tip
Input variables are not copied into the function workspace, unless
Avoid performance penalty when using large arrays by extracting only those elements that will need modification
Intro MATLAB
77
Intro MATLAB
78
Intro MATLAB
79
Common OS Commands
Intro MATLAB
80
Running OS Commands
The system command can be used to run OS commands On Unix systems, the unix command can be used as well On DOS systems, the corresponding command is dos >> dos('date') The current date is: Thu 01/04/2007 Enter the new date: (mm-dd-yy) ans = 0
Intro MATLAB
81
Lab 1
Create, perhaps using for-loops, a synthetic image that has a 1 in the (1,1) location, and a 255 in the (128,128) location, and i + j - 1 in the i, j location. This we'll refer to as the diagonal gray'' image. Can you manage to do this without using for-loops? Display the image using (well assume you placed your image in a matrix named a) image(a); colormap(gray). (Dont worry if this doesnt work exactly the way you expect. Colormaps can be tricky!) Now convert your code to a MATLAB script Test your script to insure that it produces the same results as the ones obtained interactively.
Intro MATLAB
82
Lab 2
Write a MATLAB function that implements Newtons iterative algorithm for approximating the square root of a number. The core of Newtons algorithm is that if last is the last approximation calculated, the next (improved) approximation is given by next = 0.5(last +(x/last)) where x is the number whose square root you seek. Two other pieces of information are needed to implement the algorithm. The first is an initial guess at the square root. (A typical starting value might be 1.0, say). The second is the accuracy required for the approximation. You might specify you want to keep iterating until you get an approximation that is good to 5 decimal places for example. Your MATLAB function should have three input arguments: x, the initial guess, and the accuracy desired. It should have one output, the approximate square root of x to the desired accuracy.
Intro MATLAB
83
Data I/O
84
.MAT files are binary files that can be transferred across platforms; as much accuracy as possible is preserved.
Load: load filename OR A = load(filename) loads all the variables in the specified file (the default name is MATLAB.MAT)
Save: save filename variables saves the specified variables (all variables by default) in the specified file (the default name is MATLAB.MAT)
Intro MATLAB
85
Intro MATLAB
86
dlmread M = dlmread(filename,delimiter,range);
reads ASCII values in file filename that are separated by delimiter into variable M; most useful for numerical values. The last value in a line need not have the delimiter following it. range = [R1 C1 R2 C2] (upper-left to lower-right corner)
range of data to be read
dlmwrite dlmwrite(filename,A,delimiter);
writes ASCII values in array A to file filename with values separated by delimiter
Intro MATLAB
87
textread [A, B, C, ...] = textread[filename, format]; [A, B, C, ...] = textread[filename, format, N]; [...] = textread[..., param, value, ...];
The type of each return argument is given by format (C-style conversion specifiers: %d, %f, %c, %s, etc) Number of return arguments must match number of conversion specifiers in format
Using textread you can specify values for whitespace, delimiters and exponent characters specify a format string to skip over literals or ignore fields
Intro MATLAB
88
textread Example
Data file, tab delimited: MATLAB m-file: Results:
Intro MATLAB
89
Import Wizard
Import ASCII and binary files using the Import Wizard. Type uiimport at the Command line or choose Import Data from the File menu.
Intro MATLAB
90
fclose: Close one or more open files fopen: Open a file or obtain information about open files fread: Read binary data from file fwrite: Write binary data to a file fgetl: Return the next line of a file as a string without line terminator(s) fgets: Return the next line of a file as a string with line terminator(s) fprintf: Write formatted data to file fscanf: Read formatted data from file
Unformatted I/O
Formatted I/O
Intro MATLAB
91
feof: Test for end-of-file ferror: Query MATLAB about errors in file input frewind: Rewind an open file fseek: Set file position indicator ftell: Get file position indicator or output
String Conversion
sprintf: Write formatted data to a string sscanf: Read string under format control
Intro MATLAB
92
fid
status = fclose(fid); 0, if successful -1, otherwise File identifier number or all for all files
Intro MATLAB
93
Formatted I/O
fscanf: [A, count] = fscanf(fid,format,size); Number successfully read File identifier number Format specifier Amount of data to read: n, [n, m], Inf
Data array
Format specifier
%-12.5e
initial % character alignment flag width and precision conversion specifier
Specifier Description %c Single character %d Decimal notation (signed) %e Exponential notation %f Fixed-point notation %g The more compact of %e or %f %o Octal notation (unsigned) %s String of characters %u Decimal notation (unsigned) %x Hexadecimal notation ...others...
Intro MATLAB
95
fgetl: line = fgetl(fid); reads next line from file without line terminator
fgets: line = fgets(fid); reads next line from file with line terminator
textread: [A,B,C,...] = textread('filename','format',N) reads N lines of formatted text from file filename
Intro MATLAB
96
Data array
feof: tf = feof(fid);
tests for end of file fseek: status = fseek(fid, offset, origin); sets the file position
MATLAB output
Since a tab counts as one character in MATLAB, you must use spaces after the name field in the data file (else get Tom 1 in name output, etc...)
Intro MATLAB
99
Intro MATLAB
100
hdf: HDF interface imfinfo: Return information about a graphics file imread/imwrite: Read/Write image from graphics file wk1read/wk1write: Read/Write a Lotus123 WK1 spreadsheet file into a matrix xlsread/xlswrite: Read/Write a matrix to a Excel spreadsheet file urlread: read data from a URL
Intro MATLAB
101
Intro MATLAB
102
Structures
Multidimensional MATLAB arrays Access elements using textual field designators Create structures by using periods (.):
>> class.name = MATLAB; >> class.day1 = 2/27/07; >> class.day2 = 2/28/07; >> class class = name: MATLAB day1: 2/27/07 day2: 2/28/07
Intro MATLAB
103
Manipulating Structures
Structures are arrays (no surprise) Fields can be added one at a time: >> class(2).name = MPI; >> class(2).day1 = TBA; >> class(2).day2 = TBA; Can also use a single statement: >> class(2) = struct(name,MPI,... day1,TBA,day2,TBA)
Intro MATLAB
104
Intro MATLAB
105
Intro MATLAB
106
Lab 1
The data file DataIO_lab1.dat is a binary data file containing a 256 X 256 image. The data is stored in row order with each pixel value being a double value. Read the data in DataIO_lab1.dat into a 256 X 256 real array, and display it as a gray scale image. Here are some suggestions to help you:
Preallocate the array that will hold the image data. Use the function fopen to open the file and get a file handle. Since the data is binary, use the function fread to read the data; if you want you can read it 256 values at a time. To display the data array as an image, use the MATLAB command image If the resulting image is rotated, you can use the transpose operator to take care of that. Close the file using fclose. Scale the array so that all pixel values are between 1 and 64
What are you looking at? (FUN: experiment with non-gray colormaps )
Intro MATLAB
107
Lab 2
The data file DataIO_lab2.csv is an ASCII data file that consists of comma separated real values. There are 3000 rows and 16 columns of data. The first column corresponds to sampling instants and the next 15 columns correspond to vibration data collected from a shaker table. Write a short m-file to read the data in the DataIO_lab2.csv file and assign it to two variables: t which is a 3000 X 1 array containing the sampling instants and x which is a 3000 X 15 array containing the data on all the channels. You can use fscanf (in conjunction with fopen) or dlmread to read the data. Plot x(:,1) through x(:,15) against t. MATLAB provides another way of reading ASCII data files: textread. Use textread to read the data in DataIO_lab2.csv and assign it to the variables t and x.
Intro MATLAB
108
109
Intro MATLAB
110
Each column is the raw rpm sensor data from a different sensor used in an instrumented engine test. The rows represent the times readings were made.
Intro MATLAB
111
Note that in this case the plot command generates one time-series for each column of the data matrix
Intro MATLAB
112
1082.8
1002.7
2
But you can easily compute the mean of the entire matrix (applying a function to either a single row or a single column results in the function applied to the column, or the row, i.e., in both cases, the application is to the vector). >> mean(mean(rpm_raw)) ans = 1055.6
Intro MATLAB
113
then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1 4] >> mean(rpm_raw, 2) ans = 1045.7 1064.7 So we can easily obtain the row 1060.7 means 1055 1045
Intro MATLAB
114
2
>> max(rpm_raw) ans = 1115 1120 1043
>> max(max(rpm_raw)) ans = 1120 >> [y,i] = max(rpm_raw) y = 1115 1120 1043 i = 8 2 17
max along the columns
Intro MATLAB
115
min
>> min(rpm_raw) ans = 1053 >> min(min(rpm_raw)) ans = 961 >> [y,i] = min(rpm_raw) y = 1053 1053 i = 22 1 22
min along each column
1053
961
min of entire matrix
961
Intro MATLAB
116
Intro MATLAB
117
Intro MATLAB
118
Histogram (cont.)
>> hist(rpm_raw) %histogram of the data
Intro MATLAB
119
Histogram (cont.)
>> hist(rpm_raw, 20) %histogram of the data
Intro MATLAB
120
Histogram (cont.)
>> hist(rpm_raw, 100) %histogram of the data
Intro MATLAB
121
Intro MATLAB
122
3 10 6 15
13 8 12 1
1
1 8 12 13
Intro MATLAB
123
3 10 6 15
13 8 12 1
16 11 12 15
1 8 12 13
Intro MATLAB
124
>> [y i] = sort(magic(4)) y = i = 4 2 3 1 5 7 6 8 9 11 10 12 16 14 15 13
3
4 2 3 1 1 3 2 4 1 3 2 4 4 2 3 1
Intro MATLAB
125
This example uses an FIR filter to compute a moving average using a window size of 3
Intro MATLAB
127
The fft function can compute the discrete Fourier transform of any arbitrary length sequence. fft incorporates most known fast algorithms for various lengths (e.g. power of 2) Not all lengths are equally fast
Intro MATLAB
128
N 1
X [ k ]= x [n]e
n=0
j2 kn N
1 x [n]= N
N 1
X [ k ]e k =0
j2 kn N
Intro MATLAB
129
N=11
-
Intro MATLAB
130
Intro MATLAB
131
Frequency Spectrum
Intro MATLAB
132
Lab 1
Load the data_analysis_lab1.mat file into the MATLAB workspace. This will produce an array variable called grades containing grades on an exam between 0 and 100. Calculate the average and standard deviation of the grades. Plot a histogram of the grades using 100 bins. We want to compare the histogram with a Gaussian distribution. Write you own MATLAB Gaussian function M-file which returns a value y using the following formula y=exp(-[x-m]2/22) where m is the average and is the standard deviation of the distribution. Your function should have input arguments x,m, and . On the histogram plot also plot a Gaussian distribution of the grades using the calculated average and standard deviation.
Intro MATLAB
133
Lab 2
Load the file data_analysis_lab2.mat. Since this is a .mat file, you should be able to load it easily using the load command. Your workspace should now contain a single variable x. x is 3000 points long and consists of the sum of 3 sine waves. The sampling frequency is 1000 Hz. Plot the first 0.33 seconds of x. You may find it convenient to create a second array (say called time) that has the time values corresponding to the samples in x. >> Fs = 1000;
%Sampling frequency
>> time = [0:length(x)-1]*(1/Fs); % time index fft is a built-in function in MATLAB. We can compute and plot the magnitude of the FFT of x to identify the frequencies of the sine waves. >> X = fft(x);
X is a complex valued array that is the FFT of x. We can compute the magnitude of the FFT by taking the absolute value of X. >> Xmag = abs(X); >> plot(Xmag);
Intro MATLAB
134
Lab 2 (cont.)
The plot of Xmag shows 6 components, and also we have only index values not real frequency values along the abscissa. Six components show up because the FFT is evaluated over positive and negative frequencies. Also, the frequencies are wrapped around. We can take care of the wrap around using the fftshift function. >> Xmag = fftshift(Xmag); Next, we can generate a suitable frequency axis for plotting Xmag. >> frq = [0:length(Xmag)-1]*(Fs/length(Xmag)) (Fs/2); >> plot(frq, Xmag); Can you see the 3 frequency components (in the positive freq. part of the axis)? Zoom into the plot either using the axis command or the interactive zoom button on the figures toolbar and determine the frequencies of the 3 components.
Intro MATLAB
135
Numerical Analysis
136
Overview
IEEE double precision numbers Numerical Linear Algebra Solving linear equations (Ax b) Condition number Matrix factorizations Eigenvalues and eigenvectors Singular value decomposition Solving ODEs Numerical integration Root finding Nonlinear optimization
Intro MATLAB
137
E (11 bits)
f (52 bits)
Intro MATLAB
138
Intro MATLAB
139
Linear Equations, n = m
When A is square (i.e., n = m) and the equations are independent and consistent, the unique solution can be found using the \ operator. MATLAB finds the solution using a LU decomposition of A.
>> A = [1 2 3; 4 5 6; 7 8 0] A = 1 2 3 4 5 6 7 8 0 >> b = [366; 804; 351] b = 366 804 351 >> [rank(A) rank([A b])] ans = 3 3 >> x = A\b x = 25 22 99
Intro MATLAB
140
\ finds the solution with no more than rank(A) non-zero elements. pinv can be used to find the solution with min ||x||.
>> A = [2 3 4; 1 1 1]; b = [4;5]; >> x = A\b x = 8 0 -3 >> x1 = pinv(A)*b x1 = 7.1667 1.6667 -3.8333 >> sqrt([sum(x.^2) sum(x1.^2)]) ans = 8.544 8.2966
Intro MATLAB
141
Intro MATLAB
142
Example (cont.)
This leads to the underdetermined set of equations
A x=b
143
Intro MATLAB
Example (cont.)
>> x1 = A\b x1 = 0.11111 0 0 0 0 0 0 0 0 -0.11111 >> x2 = pinv(A) * b x2 = 0.054545 0.042424 0.030303 0.018182 0.0060606 -0.0060606 -0.018182 -0.030303 -0.042424 -0.054545 >> [norm(x1) norm(x2)] ans = 0.15713 0.1101
Intro MATLAB
144
>> A = [2 -1; 1 1; 6 -1]; >> b = [2; 5; -5]; >> [rank(A) rank([A b])] ans = \ can be used to find 2 3 the least squares solution, i.e., the x that >> x = A\b minimizes ||Ax-b||2 x = -0.094595 2.4459
Intro MATLAB
145
y=a0 a1 xa p x e
Assume e is measurement noise, and that we have n measurements of x and y. This leads to an overdetermined set of equations:
1 x1 x a0 y1 = p yn 1 xn xn a p
p 1
Intro MATLAB
146
Example (cont.)
Condition of a Matrix
Consider Ax = b. If A changes by a small amount , how large is the change in the solution x? ||x||/||x|| < (A) ||A||/||A|| (A) is the condition number of A () is calculated using the MATLAB command cond(A) Consider A essentially singular if () > 1/eps
Intro MATLAB
148
>> A = [1 1; 1 1.01] >> b = [2; 2.01]; >> x = A\b x = 1 1 >> A1 = [1 1.005; 1 1.01]; >> x1 = A1\b x1 = -0.01 2 >> cond(A) ans = 402.01
Matrix Factorizations: lu
lu: factors a square matrix A into the product of a permuted lower triangular matrix L and an upper triangular matrix U such that A = LU. Useful in computing inverses, Gaussian elimination.
>> A = [1 2 -1; 1 0 1; -1 2 1]; >> [L, U] = lu(A) L = 1 0 0 1 -0.5 1 -1 1 0 U = 1 2 -1 0 4 0 0 0 2 >> L * U ans = 1 2 -1 1 0 1 -1 2 1
Intro MATLAB
149
Intro MATLAB
150
Intro MATLAB
151
Intro MATLAB
152
Pseudoinverse: pinv
pinv: The pseudoinverse of an n x m matrix A is a matrix B such that BAB = B and ABA = A MATLAB uses the SVD of A to compute pinv. Useful in solving least squares problems.
Intro MATLAB
153
>> A = [2 -1; 1 1; 6 -1]; >> B = pinv(A) B = -0.013514 0.13514 0.14865 -0.36486 0.64865 0.013514 >> A*B*A ans = 2 -1 1 1 6 -1 >> B*A*B ans = -0.013514 0.13514 0.14865 -0.36486 0.64865 0.013514
det(A): computes determinant inv(A): computes inverse expm(A),logm(A), sqrtm(A): computes exponential, logarithm and square root of A polyvalm(p,A): evaluate matrix polynomial, p(A).
lsqnonneg(A,b): non-negative least squares norm(A): computes matrix norm orth(A), null(A): finds a basis for the range and null space of A qr(A): orthogonal-triangular decomposition of A subspace(A,B): computes angle between subspaces defined by A and B
Intro MATLAB
154
Intro MATLAB
156
Stiff equations
ode23: explicit, one-step Runge-Kutta low-order solver ode45: explicit, one-step Runge-Kutta medium order solver. First solver to try on a new problem ode113: multi-step Adams-Bashforth-Moulton solver of varying order
Intro MATLAB
157
ode23s: implicit, onestep modified Rosenbrock solver of order 2 ode15s: implicit, multistep numerical differentiation solver of varying order. Solver to try if ode45 fails or is too inefficient
d x/dt - (1-x2)dx/dt + % van der Pol equation x = 0 Convert to first order ODEs using y1 = x, y2 = dx/dt dy1/dt = y2 dy2/dt=(1-y12)y2-y1
Intro MATLAB
158
Intro MATLAB
159
Intro MATLAB
160
Numerical Integration
trapz: Trapezoidal integration quad: Adaptive, recursive Simpsons Rule for quadrature quadl: Adaptive, recursive Newton-Coates 8-panel rule dblquad: Double integration using quad or quadl
Intro MATLAB
161
Intro MATLAB
162
fminbnd, fminsearch: finds maxima and minima of functions of one and several variables
Intro MATLAB
163
p(x)=x3+4x2-7x-10
Intro MATLAB
164
Intro MATLAB
165
Intro MATLAB
166
Lab 1
Consider the set of equations Ax=b where A is an 8x8 matrix given by A(i,j)=1.0+(|i-j|/8.0) and b is a 8x1 array given by b(i)=i Solve for x using: The \ operator The MATLAB pinv function The MATLAB inv function LU Decomposition How do your answers compare? For best performance, evaluate the matrix A without using any for loops
Intro MATLAB
167
Lab 2
Use numerical integration to integrate 1/(1+x2) from 0 to 1. The result is analytically calculated to be /4. Use the following three MATLAB functions:
and compare the accuracy of your numerical result with the exact value. Use quad or quadl to get the most accurate result possible with MATLAB. How accurate is it?
Intro MATLAB
168
169
Overview
Plots Simple plots Subplots (Multiple Axis Regions) Mesh plots (Colored wire-frame view of surface) Surface Plots Patches Contour Plots Visualization Images Indexed images Intensity images Truecolor images Reading and writing images Movies
Intro MATLAB
170
Basic XY Plot
>> x = [0:pi/100:pi]; >> y = sin(x); >> plot(x,y), title('Simple Plot')
Intro MATLAB
171
Intro MATLAB
172
Subplots
Used to display multiple plots in the same figure window, subplot(m,n,i) subdivides the window into m-by-n subregions (subplots) and makes the ith subplot active for the current plot
>> subplot(2,3,1) >> plot(t, sin(t), 'r:square') >> axis([-Inf,Inf,-Inf,Inf])
1
3 2
>> subplot(2,3,3) >> plot(t, cos(t), 'g') >> axis([-Inf,Inf,-1,1]) >> subplot(2,3,5) >> plot(t, sin(t).*cos(t), 'b-.') >> axis([-Inf,Inf,-Inf,Inf])
4
Intro MATLAB
174
Mesh Plots
MATLAB defines a surface by the z-coordinates of points above a rectangular grid in the x-y plane Plot is formed by joining adjacent defining points with straight lines Surface plots are used when matrices are too large to visualize numerically, and also to graph functions of two variables Use to generate a colored wire-frame view of a surface displayed in a 3-D view Only the lines connecting the defining points are colored mesh(Z) generates a wireframe view of matrix Z, where Z(i,j) define the height of a surface over the rectangular x-y grid:
>> >> >> >> figure(2); [X,Y] = meshgrid(-16:1.0:16); Z = sqrt(X.^2 + Y.^2 + 5000); mesh(Z) Intro MATLAB
175
Surface Plots
surf(Z) generates a colored faceted 3-D view of the surface. By default, the faces are quadrilaterals, each of constant color, with black mesh lines The shading command allows you to control the view
>> >> >> >> figure(2); [X,Y] = meshgrid(-16:1.0:16); Z = sqrt(X.^2 + Y.^2 + 5000); surf(Z) Default: shading faceted >> shading flat >> shading interp
Intro MATLAB
176
Intro MATLAB
177
>> meshz(Z)
>> surfl(Z)
>> pcolor(Z)
Intro MATLAB
178
Patches
A patch is a graphics object which contains one or more polygons. The polygons dont have to be connected Useful for modeling real-world objects such as missiles and tanks Use the patch function to display a patch One way to define a patch is to specify Faces and Vertices
Vertices, v Vertex 1 Vertex 2 Vertex 3 Vertex 4 Vertex 5 Vertex 6 Vertex 7 Vertex 8 0 1 1 0 0.25 0.75 0.75 0.25 0 0 1 1 0.25 0.25 0.75 0.75 0 0 0 0 1 1 1 1 Face 1 Face 2 Face 3 Face 4 Face 5 Face 6 1 5 1 2 3 4 Faces, f 2 6 2 3 4 1 3 7 6 7 8 5 4 8 5 6 7 8
Intro MATLAB
179
Intro MATLAB
180
Contour Plots
Use to create, display, and label isolines determined by one or more matrices contour(Z) generates isolines from values given by a matrix Z and displays it in 2-D contour3(Z) generates isolines from values given by a matrix Z and displays it in 3-D
>> Z = peaks; >> contour(Z,40) >>
Intro MATLAB
181
Intro MATLAB
182
Visualization: Light
Technique for adding photo-realistic appearance to a graphical scene Use light to create lighting effects in MATLAB in conjunction with the following three important properties >> set(L1, 'Color', 'g') Color Style Position
Intro MATLAB
183
Intro MATLAB
184
Visualization: Viewpoint
Use view to specify the viewpoint by defining azimuth and elevation with MATLAB defaults respect to the origin
For 2-D plots, azimuth = 0o elevation = 90o For 3-D plots, azimuth = -37.5o elevation = 30o
z y
Elevation Default View >> view(-37.5, 60);
x
Azimuth
-y
Intro MATLAB
185
Default View
>> set(gca,'Projection','perspective')
Intro MATLAB
186
CameraPosition: Position adjusted such that the orientation of the scene is the standard MATLAB 2-D or 3-D view
CameraUpVector: y-direction for 2-D views and z-direction for 3-D views
CameraViewAngle: Angle adjusted such that scene fills the position rectangle
Projection: orthographic
Intro MATLAB
187
Indexed Images
Consists of a data matrix, I and a colormap matrix, C C is an m-by-3 matrix, with each row specifying the R, G, and B components of a single color Values in C are floating point numbers in the range [0, 1] Color of each pixel is determined by using the corresponding value of I as an index into the colormap
R 1 G 0 1 1 B 0 0 1 2
10
0.5
0.5
0.5
10
I
Intro MATLAB
188
0.35
0.25 m
Intensity Images
Consists of a data matrix, I, whose values represent intensities within some range.
For double-precision data, the intensity values are in the range [0, 1], where 0 represents black, and 1 represents white. Values in between 0 and 1 represent shades of gray
Use the following to display intensity images. >> imagesc(I, [0, 1]); colormap(gray);
The second input argument [0, 1] to imagesc specifies the desired intensity range. I is displayed by first mapping the first value in the range to the first colormap entry, and second value in the range to the last colormap entry. Values in between are mapped linearly.
To automatically map the minimum value in I to the first colormap entry, and the maximum value in I to the last colormap entry, do the following. >> imagesc(I); colormap(gray);
Intro MATLAB
189
HumVee(:, :, 1)
Intro MATLAB
190
Intro MATLAB
191
Reading Images
MATLAB can read images of various formats including
BMP, HDF, JPEG, PCX, TIFF, XWD imread reads indexed, intensity, and truecolor images Images are read into a uint8 matrix of appropriate size
imread automatically determines the format of the image based on information in the header
Intro MATLAB
192
Intro MATLAB
193
Writing Images
MATLAB can write images of various formats including the following
BMP, HDF, JPEG, PCX, TIFF, XWD
imwrite determines the format from extension of filename. You can specify an optional format if extension is absent or to force a particular format
Intro MATLAB
194
Grand total is 981120 elements using 981120 bytes >> % Write out tank as gray image >> AbramsGray = rgb2gray(Abrams); >> colormap gray; >> image(AbramsGray) >> imwrite(AbramsGray, gray, 'Abrams.bmp');
Intro MATLAB
195
getframe returns a movie frame by taking a snapshot of the current axis. For example, F=getframe; im2frame converts an indexed image into movie format. For example, F=im2frame(A,MAP) returns the frame as an indexed image matrix A and a colormap MAP.
A MATLAB movie array can be played back by the movie command. movie(M,N,FPS) plays the movie M for N times at FPS frames per second. The default if FPS is omitted is 12 fps.
Intro MATLAB
196
Intro MATLAB
197
movie2avi(M,FILENAME,PARAM,VALUE,PARAM,VALUE...) creates an AVI file from the MATLAB movie M using the specified parameter settings. Available parameters are
FPS - The frames per second for the AVI movie. The default is 15 fps. COMPRESSION - A string indicating the compressor to use. For example, Indeo3, Indeo5, Cinepak, MSVC, or None. QUALITY - A number between 0 and 100. Higher quality numbers result in higher video quality and larger file sizes. The default is 75. KEYFRAME - For compressors that support temporal compression, this is the number of key frames per second. The default is 2 key frames per second. COLORMAP - An M-by-3 matrix defining the colormap to be used for indexed AVI movies. VIDEONAME - A descriptive name for the video stream. This parameter must be no greater than 64 characters long. The default name is the filename.
Intro MATLAB
198
Example that Illustrates the Use of Movies to Visualize the Various Powers of the N-th Root of Unity, exp(2pi / n)
figure(1) numframes=16; % gca: get current axis; returns handle to the % current axes for the current figure set(gca, NextPlot', 'replacechildren') axis equal % fix the axes for k=1:numframes plot(fft(eye(k+16))); % eye: Identity matrix A(k)=getframe; end movie(A)
Intro MATLAB
199
aviread
Refer to Example 1 in movie documentation (doc movie) to create frame array F using getframe then:
>> movie2avi(F, wave.avi) >> M = aviread(wave.avi) >> movie(M)
This can create some very large files! aviread can only read Type-2 Digital Video AVI files
Intro MATLAB
200
Lab 1
Show views from various angles of the surface defined by the following function: z = |x| * exp(-x2-y2) * y in MATLAB, use: Z = abs(X) .* exp(-X .^ 2 Y .^ 2) .* Y; Define an x-y grid with x and y in [-2, 2] with increments of 0.2. Show a total of 6 views in the same figure. Camera parameters for each view should appear in the title for the sub-image. Detailed Instructions Use meshgrid to define the grid ([X, Y] = meshgrid(-2:0.2:2, -2:0.2:2);) Use subplot to get multiple plots in the same figure Use surfc for the first three plots, and surf for the remaining three plots Use the shading and view functions to achieve desired appearance and view Set the title for each view using the title function Use axis tight to make the surface fill the extent of the axes for each view Use axis vis3d to preserve aspect ratio for different views Set the size and position of the figure window using the set function.
Intro MATLAB
201
Inter-Language Programming
202
MEX Basics
MEX stands for MATLAB EXecutable MEX files are C and FORTRAN programs that are callable from MATLAB after compiling Why? Pre-existing C/FORTRAN programs can be called from MATLAB without rewriting codes in MATLAB Computations that do not run fast enough in MATLAB, such as for loops, can be coded in C or FORTRAN for efficient implementation. Access to hardware such as A/D, D/A converters, GPIB hardware, serial/parallel port, etc. Protect intellectual property
Intro MATLAB
203
MEX Procedure
Procedures for working with MATLABs MEX mechanism 1. Prepare the C or Fortran MEX program according to MATLAB external interfacing rules 2. Compile the C or FORTRAN MEX program using MATLAB command mex 3. mex in turn makes use of external C or FORTRAN compilers 4. Call the compiled MEX function in the same way as calling any MATLAB function
Intro MATLAB
204
Intro MATLAB
205
mxArray *plhs[],
Number of RHS arguments
int nrhs,
Pointer to array of of RHS argument pointers
Intro MATLAB
206
>> [a b] = timestwo(x,y);
Intro MATLAB
207
nlhs = 1 plhs a
nrhs = 1 prhs x
(matrix)
Intro MATLAB
208
MEX Procedure
1. Compile timestwo.c using mex command in MATLAB
>> mex timestwo.c >> dir *.mexw32 timestwo.mexw32
Intro MATLAB
209
timestwo.c
include mex.h Gateway function and its 4 arguments Dynamically allocate memory for the output array Processing the input parameters
#include mex.h // do not forget this void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *p,*n; // pointers to output and input arrays int i,j,m,n; // indices and dimension variables if (nrhs != nlhs) // Error Check mexErrMsgTxt(Number of input and output args differ"); for(i = 0; i < nrhs; i++) { m = mxGetM(prhs[i]); n = mxGetM(prhs[i]); // get dims plhs[i] = mxCreateDoubleMatrix(m,n,mxREAL); data1 = mxGetPr(prhs[i]); // retrieve input data2 = mxGetPr(plhs[i]); // create pointer to output for(j = 0; j < m*n; j++ { data2[j] = 2 * data1[j]; } } }
Intro MATLAB
210
Sample script:
#PBS -l nodes=1:ppn=1 #PBS -l walltime=1:00:00 module load matlab matlab -nodisplay < myscript.m
211