You are on page 1of 211

Introduction to MATLAB

Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212 http://www.osc.edu/supercomputing/training/

Functions - Scope of Activity


Supercomputing. Computation, software, storage, and support services empower Ohios scientists, engineers, faculty, students, businesses and other clients. Networking. Ohios universities, colleges, K-12 and state government connect to the network. OSC also provides engineering services, video conferencing, and support through a 24x7 service desk. Research. Lead science and engineering projects, assist researchers with custom needs, partner with regional, national, and international researchers in groundbreaking initiatives, and develop new tools. Education. The Ralph Regula School of Computational Science delivers computational science training to students and companies across Ohio.

Intro MATLAB
2

Instructor and STS Contact Info


Brian Guilfoos guilfoos@osc.edu 614-292-2846 http://www.osc.edu/supercomputing/training/ Science and Technology Support (STS) Group: Monday Friday, 9am-12pm, 1pm-5pm oschelp@osc.edu (preferred contact method) 614-292-1800 800-686-6472
Intro MATLAB
3

Table of Contents Day One Overview Basic Interfaces Arrays, Matrices, Operators Programming Data I/O

Intro MATLAB
4

Table of Contents Day Two

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

Toolboxes, Software, & Links

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

Online MATLAB Resources


www.mathworks.com/ www.mathtools.net/MATLAB www.math.utah.edu/lab/ms/matlab/matlab.html web.mit.edu/afs/athena.mit.edu/software/matlab/ www/home.html www.utexas.edu/its/rc/tutorials/matlab/ www.math.ufl.edu/help/matlab-tutorial/ www.indiana.edu/~statmath/math/matlab/links.html www-h.eng.cam.ac.uk/help/tpl/programs/matlab.html

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

Some More Resources


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
Intro MATLAB
14

Basic Interfaces

15

Main MATLAB Interface

Intro MATLAB
16

Some MATLAB Development Windows


Command Window: where you enter commands Command History: running history of commands which is preserved across MATLAB sessions Current directory: Default is $matlabroot/work Workspace: GUI for viewing, loading and saving MATLAB variables Array Editor: GUI for viewing and/or modifying contents of MATLAB variables (openvar varname or double-click the arrays name in the Workspace) Editor/Debugger: text editor, debugger; editor works with file types in addition to .m (MATLAB m-files)
Intro MATLAB
17

MATLAB Editor Window

Intro MATLAB
18

MATLAB Help Window (Very Powerful)

Intro MATLAB
19

Command-Line Help : List of MATLAB Topics


>> help HELP topics:

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

Command-Line Help : List of Topic Functions


>> help matfun Matrix functions - numerical linear algebra. Matrix analysis. norm normest rank det trace null orth rref subspace

- 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

Command-Line Help : Function Help


>> help det DET Determinant. DET(X) is the determinant of the square matrix X. Use COND instead of DET to test for matrix singularity. See also cond. Overloaded functions or methods (ones with the same name in other directories) help laurmat/det.m Reference page in Help browser doc det

Intro MATLAB
22

Keyword Search of Help Entries


>> lookfor who newton.m: % inputs: 'x' is the number whose square root we seek testNewton.m: % inputs: 'x' is the number whose square root we seek WHO List current variables. WHOS List current variables, long form. TIMESTWO S-function whose output is two times its input. >> whos Name ans fid i

Size 1x1 1x1 1x1

Bytes 8 8 8

Class double double double

Attributes

Intro MATLAB
23

startup.m
Customize MATLABs start-up behavior Create startup.m file and place in:

Windows: $matlabroot\work UNIX: directory where matlab command is issued

My startup.m file:

addpath e:\download\MatlabMPI\src addpath e:\download\MatlabMPI\examples addpath .\MatMPI format short g format compact

eliminates extra blank lines in output

Intro MATLAB
24

Variables (Arrays) and Operators

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

mixed data types

semi-colon suppresses output of the calculations result

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)

Terminology: scalar (1 x 1 array), vector (1 x N array), matrix (M x N array)

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.

Roughly 31 times faster without use of for loop

Intro MATLAB
30

Matrices: Magic Squares


This matrix is called a magic square

Interestingly, Durer also dated this engraving by placing 15 and 14 side-by-side in the magic square.

Intro MATLAB
31

Durers Matrix: Creation


durer1N2row = [16 3 2 13; 5 10 11 8]; durer3row = [9 6 7 12]; durer4row = [4 15 14 1]; durerBy4 = [durer1N2row;durer3row;durer4row]; durerBy4 durerBy4 = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1

Intro MATLAB
32

Easier Way...
durerBy4 = 16 3 5 10 9 6 4 15 2 11 7 14 13 8 12 1

durerBy4r2 = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] durerBy4r2 = 16 5 9 4 3 10 6 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

concatenation with blank or with ,

semi-colon: join vertically

Intro MATLAB
35

Character Strings as Arrays


>> greetings greetings = helloMATLAB >> vgreetings = [hi;class] vgreetings = hello MATLAB >> hi = 'hello' hi = hello >> vgreetings = [hi;class] ??? Error using ==> vertcat CAT arguments dimensions are not consistent.

note deleted space at beginning of word; results in error

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

returns 1 if argument is a character array and 0 otherwise

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]

>> isequal(a,b) ans = 0 >> ismember(a,b) ans = 0 0 1 1 1

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

>> row_sums = sum(durer')' row_sums = 34 34 34 34

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

The Other Diagonal


>> durer durer = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1

>> fliplr(durer) % flip left-right ans = 13 2 3 16 8 11 10 5 12 7 6 9 1 14 15 4 >> sum(diag(fliplr(durer))) ans = 34

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

Colon Operator (Vector Creation)


>> 1:5 % use the colon operator to create row vectors ans = 1 2 3 4 5

>> 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

Colon Operator (Indexing)


>> sum(durer(1:3,4)) % sums first three % elements of column 4 ans = 33

>> sum(durer(:,end)) % a lone colon is ALL % elements, end is % the last element ans = 34
Intro MATLAB
45

The Dot Operator


By default and whenever possible MATLAB will perform true matrix operations (+ - *). The operands in every arithmetic expression are considered to be matrices. If, on the other hand, the user wants the scalar version of an operation a dot must be put in front of the operator, e.g., .*. Matrices can still be the operands but the mathematical calculations will be performed element-by-element. A comparison of matrix multiplication and scalar multiplication is shown on the next slide.
Intro MATLAB
46

Dot Operator Example


>> A = [1 5 6; 11 9 8; 2 34 78] A = 1 11 2 B = 16 8 67 4 123 259 23 86 5
Intro MATLAB
47

5 9 34

6 8 78

>> B = [16 4 23; 8 123 86; 67 259 5]

Dot Operator Example (cont.)


>> C = A * B C = 458 784 5530 >> CDOT = A .* B CDOT = 16 88 134 20 1107 8806
Intro MATLAB
48

% normal matrix multiply 2173 3223 24392 483 1067 3360

% element-by-element 138 688 390

Two Division Operators


Right divide (familiar version) a/b What happens: a is divided by b Right operand goes into left operand Left divide a\b What happens: b is divided by a Left operand goes into right operand Behavior depends on operands (scalar vs. matrix)

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

Using the Division Operators


>> x = 53.0; >> y = 22.5; >> x/y ans = 2.3556 >> x\y ans = 0.4245 >> (x/y)^(-1) ans = 0.4245

For matrix operands, A\B is the solution to Ax = B obtained by Gaussian elimination.


Read Arithmetic Operators + - * / \ ^ in MATLAB Function Reference: Help Search for: division

Intro MATLAB
50

Easy 2-D Graphics


>> x = [0: pi/100: pi]; % [start: increment: end] >> y = sin(x); >> plot(x,y), title('Simple Plot')

Intro MATLAB
51

Adding Another Curve


>> z = cos(x); >> plot(x,y,'g.',x,z,'b-.'),title('More complicated')

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

m-file Editor Window

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

Scripts and Functions


Scripts do not accept input arguments, nor do they produce output arguments. Scripts are simply MATLAB commands written into a file. They operate on the existing workspace. Functions accept input arguments and produce output variables. All internal variables are local to the function and commands operate on the function workspace. A file containing a script or function is called an m-file If duplicate functions (names) exist, the first in the search path (from path command) is executed.

Intro MATLAB
58

Functions First Example


function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; Write these two lines to a file myfun.m and save it on MATLABs path

>> 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

Example: deLaunay Triangulation


Have a set of random (x,y) points and want to connect them together to make a triangular grid The deLaunay algorithm creates a set of triangles such that no (other) data points are contained within the area or perimeter of any given triangle. Creates an orthogonal set of triangles The resulting grid is useful as a coordinate system

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

MATLAB script: mydelaunay.m


% deLaunay triangulation % ---------------------% You must have variables x, y, and z instanced % in the workspace 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
62

Using the mydelaunay script


>> x = randn(1,12); % generates 12 normally distributed numbers >> y = randn(1,12); >> z = zeros(1,12); % trimesh (used below) needs three arguments >> mydelaunay

Intro MATLAB
63

Function: Header/Help Comments


function angles = ortho(a,b,c) %ortho function input: Three vectors each with 3 elements % % % % % % % % The output is a 3-element array containing the angles between each pair of input vectors. The output elements are respectively: angle between a and b angle between b and c angle between a and c Typical use or ortho is to determine if a,b,c form an orthogonal basis set that spans 3-D space. All initial comment lines are displayed when help is used on a function NOTE: This function should be saved in a file named ortho.m

H1 (help 1) line displayed when using lookfor

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

Using Your ortho Function


>> a = [1 2 3]; >> b = [4 5 6]; >> c = [7 8 9]; >> ortho(a,b,c) ans = 12.9332 3.4470 16.3801 >> a = [22 0 0]; >> b = [0 5 0]; >> c = [0 0 13]; >> ortho(a,b,c) ans = 90 90 90

Intro MATLAB
66

Getting ortho Function Help


>> help ortho ortho function input: Three vectors each with 3 elements The output is a 3-element array containing the angles between each pair of input vectors. The output elements are respectively: angle between a and b angle between b and c angle between a and c Typical use or ortho is to determine if a,b,c form an orthogonal basis set that spans 3-D space. >> help sin SIN Sine. SIN(X) is the sine of the elements of X. See also asin, sind.

Intro MATLAB
67

Function Syntax Summary


If the m-file name and function name differ, the file name takes precedence Function names must begin with a letter First line must contain function followed by the most general calling syntax Statements after initial contiguous comments (help lines) are the body of the function Terminates on the last line or a return statement

Intro MATLAB
68

Function Syntax Summary (cont.)


error and warning can be used to test and continue execution (error-handling) Scripts called in m-file functions are evaluated in the function workspace Additional functions (subfunctions) can be included in an m-file Use which command to determine precedence, e.g., >> which title C:\MATLAB71\toolbox\matlab\graph2d\title
Intro MATLAB
69

Variable Argument Lists


varargin / varargout allow variable numbers of input / output function arguments Used only inside function m-files Must be declared as the last input / output argument Declarations must be typed in lowercase

Intro MATLAB
70

Variable Argument Lists (cont.)


Consider the following function m-file: function myplot(x, varargin) plot(x, varargin{:}) All input arguments beginning with the second one are collected into the variable varargin so the function call:
myplot(x.^2,'color',[.5 .7 .3],'linestyle',o) results in varargin being a 1-by-4 cell array with the values color, [.5 . 7 .3], linestyle and o
Intro MATLAB
71

Variable Argument Lists (cont.)


Consider the m-file:
function [s, varargout] = mysize(x) nout = max(nargout,1) - 1; s = size(x); for k = 1:nout, varargout(k) = {s(k)}; end
nargout: number of output arguments in function call

The following >> [s,rows,cols] = mysize(rand(4,5)) returns s = [4 5], rows = 4, cols = 5


pack all output values into varargout cell array

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

If any input variables are changed, the variable will be copied

Avoid performance penalty when using large arrays by extracting only those elements that will need modification
Intro MATLAB
77

MATLABs Search Path


Is name a variable?
Is name a built-in function? Does name exist in the current directory? Does name exist anywhere in the search path? Discovery functions: who, whos, what, which, exist, help, doc, lookfor, dir, ls, ...

Intro MATLAB
78

Changing the Search Path


The addpath command adds directories to the MATLAB search path. The specified directories are added to the beginning of the search path.
>> path
MATLABPATH E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\toolbox\matlab\ops

>> addpath('c:\'); >> matlabpath


MATLABPATH c:\ E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\toolbox\matlab\ops

rmpath is used to remove paths from the search path

Intro MATLAB
79

Common OS Commands

ls / dir provide a directory listing of the current directory

>> ls . >> .. sample.m

pwd shows the current directory


>> pwd ans = e:\Program Files\MATLAB\R2006b\work >>

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

Loading and Saving Workspace Variables


MATLAB can load and save data in .MAT format

.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

ASCII File Read/Write


load and save can also read and write ASCII files with rows of space separated values: load test.dat ascii save filename variables (options are ascii, double, tabs, append) save example.dat myvar1 myvar2 -ascii -double

Intro MATLAB
86

ASCII File Read/Write (cont.)

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

Useful with spreadsheet data

Intro MATLAB
87

More ASCII File Read

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

format string is reused N times or entire file is read if N not given

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:

param,value pairs use doc textread for available param options

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

Low-Level File I/O Functions

File Opening and Closing

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

Low-Level File I/O (cont.)


File Positioning

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

File Open (fopen)/Close (fclose)

fid

= fopen(filename, permission); Name of file Permission requested: r, r+ w, w+ a, a+

File identifier number

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

fprintf: count = fprintf(fid, format, A,...);

Number successfully read

File identifier number

Format specifier

Data array(s) to write

fscanf and fprintf are similar to C version but vectorized


Intro MATLAB
94

Format String Specification

%-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

Other Formatted I/O Commands

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

sscanf: A = sscanf(s, format, size); reads string under format control

sprintf: s = sprintf(format, A); writes formatted data to a string

Intro MATLAB
96

Binary File I/O

[data, count] = fread(fid, num, precision);


Number successfully read File identifier number Amount to read n, [n, m],... int, double,

Data array

count = fwrite(fid, data, precision);


File identifier number array to write int, double,

Number successfully written

fread and fwrite are vectorized


Intro MATLAB
97

File Position Commands

feof: tf = feof(fid);
tests for end of file fseek: status = fseek(fid, offset, origin); sets the file position

ftell: position = ftell(fid); gets the file position

frewind: frewind(fid); rewinds the file

ferror: message = ferror(fid); inquire about file I/O status


Intro MATLAB
98

File I/O Example


Data file MATLAB m-file to read it
fid = fopen('asciiData.txt','r'); i = 1; while ~feof(fid) name(i,:) = fscanf(fid,'%5c',1); year(i) = fscanf(fid,'%d',1); no1(i) = fscanf(fid,'%d',1); no2(i)=fscanf(fid,'%d',1); no3(i)=fscanf(fid,'%g',1); no4(i)=fscanf(fid,'%g\n'); i=i+1; end fclose(fid);

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

File I/O Example (Alternative)


Cell arrays (storage mechanism for dissimilar kinds of data) offer a very flexible alternative Avoid the nuances and pitfalls of counting spaces and tabs Create a cell array to store the field name by using curly braces after variable name: name{i} = fscanf(fid, %s, 1);

curly braces are cell array constructors

%s (string) format specifier can be used here with cell array

Intro MATLAB
100

Specialized File I/O Commands

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

uigetfile: Interactively Get a Filename


[filename, pathname, filterindex] = uigetfile(Filterspec, DialogTitle); Example:

>> f = uigetfile('*.jpg;*.bmp;*.gif;*.tif','Specify Graphics File:')

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

Manipulating Structures (cont.)


Consider the simple structure >> exam.name = Jim Kirk; >> exam.score = 79; >> exam(2).name = Janice Lester; >> exam(2).score = 89; >> [exam.score] ans = 79 89 square brackets produce a
numeric row vector

Intro MATLAB
105

Manipulating Structures (cont.)


Can also create a cell array using curly braces: >> {exam.name} ans = 'Jim Kirk' 'Janice Lester'

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

Basic Data Analysis

109

Basic Data Analysis


Basic, and more advanced, statistical analysis is easily accomplished in MATLAB. Remember that the MATLAB default is to assume vectors are columnar. Each column is a variable, and each row is an observation.

Intro MATLAB
110

Vibration Sensors Data

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

Plotting the Data


>> >> >> >> plot(rpm_raw) xlabel('sample number - during time slice'); ylabel('Unfiltered RPM Data'); title(3 sequences of samples from RPM sensor)

Note that in this case the plot command generates one time-series for each column of the data matrix

Intro MATLAB
112

Average of the Data:


1
Applying the mean function to the data matrix yields the mean of each column >> mean(rpm_raw) ans = 1081.4

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

The mean Function


>> help mean MEAN Average or mean value. For vectors, MEAN(X) is the mean value of the elements in X. For matrices, MEAN(X) is a row vector containing the mean value of each column. For N-D arrays, MEAN(X) is the mean value of the elements along the first non-singleton dimension of X. MEAN(X,DIM) takes the mean along the dimension DIM of X. Example: If X = [0 1 2 3 4 5]

But we can apply the mean function along any dimension

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

max and its Index


1
MAX Largest component. For vectors, MAX(X) is the largest element in X. For matrices, MAX(X) is a row vector containing the maximum element from each column. For N-D arrays, MAX(X) operates along the first non-singleton dimension. [Y,I] = MAX(X) returns the indices of the maximum values in vector I. If the values along the first nonsingleton dimension contain more than one maximal element, the index of the first one is returned.

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

We can compute the max of the entire matrix, or of any dimension

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

Standard Deviation, Median, Covariance


>> median(rpm_raw) % median along each column ans = 1080 1083.5 1004 >> cov(rpm_raw) % covariance of the data ans = 306.4 -34.76 32.192 -34.76 244.9 -165.21 32.192 -165.21 356.25 >> std(rpm_raw) % standard deviation along each column ans = 17.504 15.649 18.875 >> var(rpm_raw) % variance is the square of std ans = 306.4 244.9 356.25

Intro MATLAB
117

Data Analysis: Histogram


HIST Histogram. N = HIST(Y) bins the elements of Y into 10 equally spaced containers and returns the number of elements in each container. If Y is a matrix, HIST works down the columns. N = HIST(Y,M), where M is a scalar, uses M bins. N = HIST(Y,X), where X is a vector, returns the distribution of Y among bins with centers specified by X. The first bin includes data between -inf and the first center and the last bin includes data between the last bin and inf. Note: Use HISTC if it is more natural to specify bin edges instead. ...

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

Data Analysis: Sorting


>> help sort SORT Sort in ascending or descending order. For vectors, SORT(X) sorts the elements of X in ascending order. For matrices, SORT(X) sorts each column of X in ascending order. For N-D arrays, SORT(X) sorts the along the first non-singleton dimension of X. When X is a cell array of strings, SORT(X) sorts the strings in ASCII dictionary order. Y = SORT(X,DIM,MODE) has two optional parameters. DIM selects a dimension along which to sort. MODE selects the direction of the sort 'ascend' results in ascending order 'descend' results in descending order The result is in Y which has the same shape and type as X. [Y,I] = SORT(X,DIM,MODE) also returns an index matrix I. If X is a vector, then Y = X(I). If X is an m-by-n matrix and DIM=1, then for j = 1:n, Y(:,j) = X(I(:,j),j); end

Intro MATLAB
122

Sorting Data (cont.)


>> magic(4) ans = 16 2 5 11 9 7 4 14

3 10 6 15

13 8 12 1

>> sort(magic(4)) ans = 4 2 3 5 7 6 9 11 10 16 14 15

1
1 8 12 13

Intro MATLAB
123

Sorting Data (cont.)


>> magic(4) ans = 16 2 5 9 4 11 7 14 >> sort(magic(4),2) ans = 2 3 13 5 6 1 8 7 4 10 9 14

3 10 6 15

13 8 12 1

16 11 12 15

>> sort(magic(4),1) ans = 4 2 3 5 7 6 9 11 10 16 14 15

1 8 12 13

Intro MATLAB
124

Sorting Data (cont.)


>> magic(4) ans = 16 2 5 11 9 7 4 14 3 10 6 15 13 8 12 1

>> [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

Bin Average Filtering


FILTER One-dimensional digital filter. Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B to create the filtered data Y. The filter is a "Direct Form II Transposed" implementation of the standard difference equation: a(1)*y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb) - a(2)*y(n-1) - ... - a(na+1)*y(n-na) >> filter(ones(1,3), 3, rpm_raw) ans = 359 351 335.67 719 724.33 667 1088.3 1081.7 1001 1084 1091.7 1004.7 1081 1073 1006.7 Intro MATLAB
126

This example uses an FIR filter to compute a moving average using a window size of 3

Filtered Data Plot

Intro MATLAB
127

Fast Fourier Transform (FFT)

fft is one of the built-in functions in MATLAB

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

Discrete Fourier Transform Definition

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

fft and fftshift


1 11

N=11

0 After fftshift N=11

-
Intro MATLAB
130

Example: FFT of sine Wave in Noise


>> >> >> >> >> >> >> >> >> >> >> >> fs = 1000; t = [0:999]*(1/fs); x = sin(2*pi*250*t); X = fft(x(1:512)); noise = 0.8*randn(size(x)); xn = x + noise; XnMag = fftshift(20*log10(abs(fft(xn(1:512))))); XnMagPf = XnMag(256:512); frq = [0:length(XnMagPf) - 1]'*(fs/length(XnMag)); plot(frq, XnMagPf) xlabel('freq. (Hz)'); ylabel('Mag. (db)');

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

IEEE Double Precision Numbers


Fundamental data type in MATLAB is a double precision value in ANSI/IEEE Standard 754 format:

E (11 bits)

f (52 bits)

s A numeric value is represented as: (-1)s (1.f) 2 (E-1023)


Roundoff: eps = 2-52 10-16 Underflow: realmin = 2-1022 10-308 Overflow: realmax = (2 - eps) * 21023 10308

eps, realmin and realmax are built in variables in MATLAB.

Intro MATLAB
138

Solving Linear Equations


Consider the set of equations Ax = b
A is an n x m matrix, x is an m x 1 vector and b is an n x 1 vector The rank of a matrix is the number of independent rows (or columns). Rank can be checked using the MATLAB command rank Equations are consistent if rank(A) = rank([A b]) independent if rank(A) = n
Uniqueness of solution Existence of solution

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

Linear Equations, n < m


When the number of equations is less than the number of unknowns (i.e., n < m), usually an infinite number of solutions exist.

\ 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

Example: Force Required to Move Object


Force, F Unit mass, velocity at time t = 0 is 0. Force on object is F(t). F(t) = xj, j - 1 < t < j, j = 1, , 10 Want total distance moved in 10 s to be 1. Want velocity at t =10 s to be 0.

Intro MATLAB
142

Example (cont.)
This leads to the underdetermined set of equations

A x=b

19/ 2 17/1 15/2 1/2 A= 1 1 1 1


x= x 1 x 10 , b= 1 0
T

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

Linear Equations, n > m


When there are more equations than unknowns (i.e., n > m), usually no solution exists.

>> 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

Example: Fit Polynomial to Data


Assume we can model data as

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.)

y = 1.64x 3 5.3x 2+ 7.69x 3


Intro MATLAB
147

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

Matrix Factorizations: chol


chol: factors a symmetric, positive definite matrix A as RTR, where R is upper triangular. Useful in solving least squares problems.
>> A = [2 -1; 1 1; 6 -1]; >> B = A'*A B = 41 -7 -7 3 >> R = chol(B) R = 6.4031 -1.0932 0 1.3435 >> R'*R ans = 41 -7 -7 3

Intro MATLAB
150

Eigenvalues and Eigenvectors: eig


eig: computes the eigenvalues, i and eigenvectors, i of a square matrix A.. i and i satisfy Ai = i i [V,D] = eig(A) returns the eigenvectors of A in the columns of V, and the eigenvalues in the diagonal elements of D.
>> A = [1 -1 0; 0 1 1; 0 0 -2]; >> [V, D] = eig(A) V = 1 1 -0.10483 0 0 -0.31449 0 0 0.94346 D = 1 0 0 0 1 0 0 0 -2 >> [A*V(:,3) D(3,3)*V(:,3)] ans = 0.20966 0.20966 0.62897 0.62897 -1.8869 -1.8869

Intro MATLAB
151

Singular Value Decomposition: svd


svd: factors an n x m matrix A as A = USVT, where U and V are orthogonal matrices, and S is a diagonal matrix with singular values of A. Useful in solving least squares problems.
>> A = [2 -1; 1 1; 6 -1]; >> [U,S,V] = svd(A) U = -0.32993 0.47852 -0.81373 -0.12445 -0.87653 -0.46499 -0.93577 -0.052149 0.34874 S = 6.4999 0 0 1.3235 0 0 V = -0.98447 -0.17558 0.17558 -0.98447

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

More Matrix Math in MATLAB

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

lscov(A, b, V): computes least square solution with known covariance

Intro MATLAB
154

Ordinary Differential Equations


MATLAB has a collection of m-files, called the ODE suite to solve initial value problems of the form M(t,y)dy/dt = f(t, y) y(t0) = y0 where y is a vector. The ODE suite contains several procedures to solve such coupled first order differential equations.
Intro MATLAB
155

Steps in ODE Solution Using MATLAB


Express the differential equation as a set of first-order ODEs M(t,y)dy/dt = f(t,y) Write an m-file to compute the state derivative function dydt = myprob(t, y)

Use one of the ODE solvers to solve the equations

[t, y] = ode_solver(myprob, tspan, y0);


Time index Solution matrix ODE solver ODE file for derivatives Solution time span [t0 tf] Initial conditions

Intro MATLAB
156

ODE Suite Solvers


Non-stiff equations

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

Example : van der Pol Equation


Equation is
2 2

function dydt = vdpol(t,y) %

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

mu = 2; dydt = [y(2);mu*(1- y(1)^2)*y(2)-y(1)];

ODE File vdpol.m

van der Pol Equation Solution


>> >> >> >> tspan = [0 20]; y0 = [2; 0]; [t, y] = ode45('vdpol', tspan, y0); plot(t, y(:,1), t, y(:,2), '--');

Intro MATLAB
159

More on ODE Solvers


There are a number of different options in specifying the ODE file. Check HELP on odefile for details. odeset and odeget can be used to set and examine the ODE solver options.

Can find events (such as max/min/zero, crossings etc.) in the solution.

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

Integration Example: humps Function


>> x = linspace(-1,2,150); >> y = humps(x); >> plot(x,y) >> format long >> trapz(x,y) % 5-digit accuracy ans = 26.344859225225534 >> quad('humps', -1, 2) % 6-digit accuracy ans = 26.344960501201232 >> quadl('humps', -1, 2) % 8-digit accuracy ans = 26.344960471378968

Intro MATLAB
162

Root Finding and Minimization

roots: finds roots of polynomials

fzero: finds roots of a nonlinear function of one variable

fminbnd, fminsearch: finds maxima and minima of functions of one and several variables

Intro MATLAB
163

Example of Polynomial Roots

p(x)=x3+4x2-7x-10

Intro MATLAB
164

Example of Roots for Nonlinear Functions

Intro MATLAB
165

Example of Function Minimization


>> p = [1 0 -2 -5]; >> x = linspace(0,2,100); >> y = polyval(p,x); >> plot(x,y) >> fminbnd('x.^3-2*x-5',0,2) ans = 0.8165 >> polyval(p,ans) ans = -6.0887

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:

trap() quad() quadl()

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

Graphics, Data Visualization & Movies

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

Multiple Curve Plots


>> z = cos(x); >> plot(x,y,'g.',x,z,'b-.'), title('More Complicated')
Line color, style, marker type, all within single quotes

Intro MATLAB
172

Plot Power: Contour & 3-D Mesh


>> t = 0:pi/25:pi; >> [x,y,z] = cylinder(4*cos(t)); >> subplot(2,1,1) >> contour(y) >> subplot(2,1,2) >> mesh(x,y,z) >> xlabel('x') >> ylabel('this is the y axis') >> text(1,-2,0.5,... '\it{Note the gap!}')

To save: print -djpeg myfigure.jpg use help print for options


Intro MATLAB
173

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

Surface Plots: Colormaps


>> colormap hot

>> colormap gray

>> colormap cool

>> colormap pink

Intro MATLAB
177

More Surface Plots


>> meshc(Z)

>> 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

Patches: MATLAB code


>> v = [0 0 0; 1 0 0 ; 1 1 0; 0 1 0; 0.25 0.25 1; 0.75 0.25 1; 0.75 0.75 1; 0.25 0.75 1]; >> f = [1 2 3 4; 5 6 7 8; 1 2 6 5; 2 3 7 6; 3 4 8 7; 4 1 5 8]; >> % Code to make top figure on previous slide >> patch('Vertices', v, 'Faces', f, 'FaceVertexCData', hsv(6), 'FaceColor', 'flat') >> view(3) >> axis square >> grid on >> clf >> % Code to make bottom figure on previous slide >> patch('Vertices', v, 'Faces', f, 'FaceVertexCData', hsv(8), 'FaceColor', interp) >> view(3) >> axis square >> grid on

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) >>

>> Z = peaks; >> contour3(Z,40) >>

Intro MATLAB
181

More Contour Plots


>> >> >> >> Z = peaks; [C, h] = contour(Z, 10); clabel(C, h); title('Labeled Contour') >> Z = peaks; >> [C, h] = contourf(Z, 10); >> title('Filled Contour') >>

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

>> set(L1, 'Position', [-1, -1, 1])

>> set(L1, 'Style', 'local')

Intro MATLAB
183

MATLAB Lighting Code


>> % This code creates the upper left figure on previous slide >> [X, Y, Z] = sphere(64); >> h = surf(X, Y, Z); >> axis square >> reds = zeros(256, 3); >> for i=1:256 reds(i, 1) = (i-1)/255; end >> colormap(reds) >> shading interp >> L1 = light('Position', [-1, -1, -1]); >> lighting phong >> set(h, 'AmbientStrength', 0.75); >> set(h, 'DiffuseStrength', 0.5);

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

>> view(0, 90);

>> view(-37.5, 90);

Intro MATLAB
185

Visualization: Camera Properties


Use the set command to modify parameters associated with a graphics object. In this case, the Camera Properties

Default View

>> set(gca,'CameraTarget',[0,0,2]) >> set(gca,'CameraPosition',[-800,-800,13])

>> set(gca,'CameraViewAngle',30) >> set(gca,'CameraUpVector',[0,1,0])

>> set(gca,'Projection','perspective')

Intro MATLAB
186

Camera Default Properties


MATLAB defaults:

CameraPosition: Position adjusted such that the orientation of the scene is the standard MATLAB 2-D or 3-D view

CameraTarget: Center of plot box

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

Truecolor Images (RGB Images)


Consist of a m-by-n-by-3 data array, I, containing the R, G, and B components for each individual pixel HumVee(:, :, 3) I(:, :, 1) is the red component of the image I(:, :, 2) is the green component of the image I(:, :, 3) is the blue component of the image To display a truecolor image, do the following >> image(I) Truecolor images do not use colormaps
HumVee(:, :, 2)

HumVee(:, :, 1)

Intro MATLAB
190

Summary: Commands to Display Images


Use the following to display an Indexed image. >> image(I); colormap(map) Use the following to display an Intensity image >> imagesc(I); colormap(map); Use the following to display a Truecolor image >> image(I);

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

Use function imread to read image files

imread automatically determines the format of the image based on information in the header

You can specify a format as an optional second argument

Intro MATLAB
192

MATLAB Code for Reading Images


>> Crusader = imread(Crusader.jpg'); >> image(Crusader) >> whos Crusader Name Crusader Size 186x250x3 Bytes 139500 Class uint8 array

Grand total is 139500 elements using 139500 bytes

Intro MATLAB
193

Writing Images
MATLAB can write images of various formats including the following
BMP, HDF, JPEG, PCX, TIFF, XWD

Use function imwrite to write image files


imwrite writes indexed, intensity, and truecolor images Images are written as a uint8 matrix (converted if necessary) of appropriate size along with colormaps (if necessary) and headers

imwrite determines the format from extension of filename. You can specify an optional format if extension is absent or to force a particular format

Use imfinfo(filename) to get information on an image file

Intro MATLAB
194

Writing Images: MATLAB code


>> Abrams = imread(Abrams.jpg'); >> image(Abrams) >> whos Abrams Name Abrams Size 511x640x3 Bytes 981120 Class uint8 array

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

Creating Movies in MATLAB


MATLAB movies are stored in an array of movie frames. For example, in a movie array M, the ith frame is M(i). A movie frame is a structure having the fields "cdata" and "colormap" which contain the image data in a uint8 matrix and the colormap in a double matrix. Movie frames can be created by following commands

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

Movie Preparation & Play

Intro MATLAB
197

MATLAB movie AVI format

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.

M = aviread(FILENAME) reads the AVI movie FILENAME into a movie array M.

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

MEX Include File : mex.h


Must be included in all MEX Files source code Defines the prototypes of all mex* API functions (e.g. mexErrMsgTxt() in our example ) mex* functions used to set up program tasks Includes matrix.h, which in turn defines the prototypes of all mx* API functions (e.g. mxGetN() in our example) mx* functions used for data variables

Intro MATLAB
205

Gateway Function : mexFunction()


Equivalent to main() in C programs
Has 4 arguments
void mexFunction (int nlhs,
Pointer to array of of LHS argument pointers Number of LHS arguments

mxArray *plhs[],
Number of RHS arguments

int nrhs,
Pointer to array of of RHS argument pointers

const mxArray *prhs[])

Intro MATLAB
206

Sample Problem: Scaling


Simple example: A C function that takes its input, multiplies each element by 2, and then returns the scaled-up values Straightforward C task chosen so that MEX requirements can be emphasized Resulting C MEX file is general purpose in nature How the function might be used in MATLAB:

>> [a b] = timestwo(x,y);
Intro MATLAB
207

mexFunction in Scaling Example


In MATLAB: >> a = timestwo(x) In timestwo.c:
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])

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

Compiling mex program, timestwo.c


A platform-specific binary is generated after compiling

2. Use timestwo.mexw32 like any MATLAB command


>> [a b] = timestwo(5,6) a = 10 b = 12

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

Using MATLAB on Glenn

Batch NB: procedure may change, if so it will be documented on the website

Sample script:

#PBS -l nodes=1:ppn=1 #PBS -l walltime=1:00:00 module load matlab matlab -nodisplay < myscript.m

211

You might also like