Chemical Engineering 541
Computer Aided Design Methods
Matlab Tutorial
1
2
Overview
• Matlab is a programming language suited to numerical analysis and
problems involving vectors and matricies.
– Matlab = Matrix Laboratory
– Many built in functions for solution of linear systems, interpolation,
integration, solution of ODEs, etc.
– Straightforward syntax
– No need for external compilation/linking
• Built in 2D, 3D graphics, very flexible
• Can interface with C++, Java, Fortran
• Object oriented programming capabilities
• Graphical interface.
• Built-in debugging capability.
• Great for rapid programming/prototyping.
– Excellent learning environment, ideas carry over to faster, more flexible
(and complex) languages, such as C, Fortran.
3
FreeMat, Octave, Scilab
• Freemat, Octave, and SciLab are open source, Matlab-like variants
• Octave contains fewer features, but very similar syntax, and runs most
Matlab scripts without modification.
– Visualization is via gnuplot
• Scilab has a Matlab-like look and feel.
• Freemat has a nice interface, and good plotting capabilities.
• www.gnu.org/software/octave, www.scilab.org, http://freemat.sourceforge.net
4
Environment
Command Window
Editor Window
Variables
History
5
Matlab Search Path
• File >> set path
• Organize files into one or
more place as you create
them.
– This goes for other
environments/languages
as well.
• Search path: EDU>> myvar
1. variable?
2. built-in function?
3. script file in current
directory?
4. Matlab path?
5. Error
6
Defining Variables, Expressions
• Expressions are saved to ans
• Variables are case sensitive: no spaces, start with a
letter.
• Semicolon supresses output to screen
• Variables defined, use who, whos
• Special Vars:
ans, beep, pi, eps, inf, NaN, i, j, nargin, nargout, realmin, realmax,
bitmax, varargin, varargout
• Reserved Words
for end if while function return elseif case otherwise switch
continue else try catch global persistent break
• Operators: + - * / \ ^
• Comments: EDU>> a=b+c; % this is a comment
7
Vectors and Matricies
• Vectors, Matricies, Arrays are
synonymous
• Enter elements between [ ... ]
– column elements separated by “,”
or “ “
– rows separated by “;”
– transpose with single quote.
– elements can be expressions
• Access elements with mat(index)
– indexing starts at 1
– Column notation
– end
– index can be an array
– note index increment:
• istart : inc : iend
8
Array Construction
Array Construction Summary Standard arrays
• Scalars operate directly on array elements:
EDU>> g = [1 2 3; 4 5 6; 7 8 9];
EDU>> g-2; 2*g-1, etc.
• Array-Array operations are as in matrix algebra
EDU>> h = [5 6 7; 8 9 10; 11 12 13];
EDU>> g+h; 2*g+h; etc
• Matrix multiplication:
EDU>> g*h;
• Matrix element operations:
EDU>> g.*h; g.^h; sin(g); 1./g; g.^2; etc.
9
More Array Operations
• Automatic expansion possible
• Reshape function operates on
columns.
• Automatic deletion
• repmat function to create new
matricies from existing matrices.
• Other functions
– sort, find, flipud, fliplr, rot90,
max, min.
– length, size, numel, A(:)
10
m-files
• m-files are script files containing batches of
matlab commands
– save and edit myfile.m
– run EDU>> myfile to execute commands.
– these files constitute the program and are the usual
mode of use except for simple jobs at the command
prompt.
– files can call other files for code organization
• think of the execution of commands as if typed directly at the
command prompt.
– useful functions: clc, clear, tic, toc, date, diary, format
11
Functions
• Purpose of functions. • Function content
– Organize code – input arguments
– Reuse functionality – return values
• simplifies code
• Function file
• easier to maintain
– name
• Variable Scope
– subfunctions
– Variables are local to the
– M-file calls
function, and can only be
used in the function.
– global statement allows
variable access.
• global var1 var2 ...
• naming
– persistent
12
Function Syntax
function a = functionName(arg1, arg2, ...)
function [a, b, c] = functionName(arg1, arg2, ...)
• Name the function M-file
functionName.m
• Input arguments
– pass in when called
– can be any type (e.g. an
array)
– can pass fewer than
needed
• Return values
– these are the outputs
– one or many
– again any type
[x,y] = ftest(2,3);
• varargin, varargout
[x,y] = ftest(1:4, 7:10);
13
Function Documentation
EDU>> open linspace
• Documenting
functions is good EDU>> help linspace
code practice
– Eases maintenence
to you and others function y = linspace(d1, d2, n)!
%LINSPACE Linearly spaced vector.!
• Purpose of the % LINSPACE(X1, X2) generates a row vector of 100 linearly!
function % equally spaced points between X1 and X2.!
%!
• Example of useage % LINSPACE(X1, X2, N) generates N points between X1 and X2.!
• What are the inputs/ % For N < 2, LINSPACE returns X2.!
%!
outputs % Class support for inputs X1,X2:!
• Any issues, % float: double, single!
%!
limitations, suggested % See also LOGSPACE, :.!
improvements.
% Copyright 1984-2004 The MathWorks, Inc. !
• Initial continuous % $Revision: 5.12.4.1 $ $Date: 2004/07/05 17:01:20 $!
comments are
displayed with help if nargin == 2!
n = 100;!
funcName end!
n = double(n);!
y = [d1+(0:n-2)*(d2-d1)/(floor(n)-1) d2];floo!
14
Visualization: 2-D Plots
• x=1:0.1:10;
• plot(x)
• plot(x,sin(x))
• General: plot(x,y,’S’)
– S is color, symbol, line style
– Example: plot(x,y,’gx--’);
Color Symbol Line Style
15
Multiple Plots
• Three methods for
multiple plots
1. hold on, hold off
2. plot x and columns of y
3. successive triplets of plot
arguments.
3
16
Subplot
• Subplot allows
multiple plots in a
matrix format
• subplot(nx,ny,pos)
activates an nx by ny
matrix of plots with
plot pos selected
17
Labeling, Formatting
18
Other Plotting Commands
• grid on; grid off;
• axis auto (manual tight, • Latex capable text
fill, on, off, square, etc.) formatting:
• axis([xmin, xmax, ymin,
• \alpha, \beta,
ymax]); or axis(array);
\gamma, \delta, etc.
• xlim([xmin, xmax]), ylim
([ymin, ymax]); • \it italic
• figure; • ^ superscript
• figure(n) • _ subscript
• close • texlabel(‘lambda =
• close(n) 3*alpha’)
• semilogx; semilogy; loglog • title('{\itAe}^{\alpha
• surf(X,Y,Z), mesh(X,Y,Z) \itt}sin\beta{\itt}
– shading flat (or interp ...) \alpha<<\beta')
19
Conditionals
• Relational Operators: • Conditionals:
– <, <=, >, >=, ==, ~= if expression if expression if expression
(command) (command) (command)
– (a+b) == (c+d) else elseif expression
end
– B - (A>2) (command) (command)
end else
• Logical Operators: (command)
end
– and: &, or: |, not: ~
– (a>2) & (a<6)
• Switch-Case
switch expression
case test_1
(commands)
case {test_2, test_2}
(commands)
otherwise
(commands)
end
20
Loops
for x = array for i = 1:10
(commands) x(i)=sin(i)
• loops offer explicit control end end
over element assignment and
other operations
for i = 1:10
• Preallocate arrays before for j= 1:3
loops. A(i,j) = i^2 + j^2;
• Loops can be nested end
end
• break statement
• Avoid for loops whenever i = 1:10;
j = 1:3;
there is an equivalent array [ii,jj] = meshgrid(i,j);
approach. A = ii.^2 + jj.^2;
– Vectorized solutions are
often orders of magnitude
faster! tend = 10;
– less typing, easier to read, t = 0;
more intuitive dt = 1.1;
while t < tend
• While loops execute till some (commands)
expression holds t = t + dt;
end
21
Basic File I/O
• save -ASCII filename x y
– saves variables x, y to the file filename
• if omitted, all variables saved
– -ASCII writes a text file
• if omitted, a binary file results (smaller)
– file called filename.mat
• load filename x y
– load the saved varialbes
– if x y is omitted, all variables are loaded
• dlmread, dlmwrite, textread, others
• fopen, fclose, fread, fwrite, fscanf, fprintf, sprintf,
sscanf, others
– myfile = ‘filelist’
– f1 = fopen(myfile);
– file = fscanf(f1, ‘%s’, 1)
22
File I/O Example
[nfiles, d1] = size(flist);
clc; clear;
for ifi=1:nfiles
myfile = 'CO2List'; f1 = fopen(flist{ifi,1});
ln = fgetl(f1);
f1 = fopen(myfile); i=1;
while(~feof(f1))
i = 1; ln = fgetl(f1);
while(1); A(i,:) = [sscanf(ln,'%f')]';
file = fscanf(f1, '%s', 1); i = i+1;
if(feof(f1)) break; end end
flist{i,1} = file; fclose(f1);
file = strrep(file, '_', ' '); if(ifi==1)
times(i,1) = sscanf(file, '%*s %*s %f'); mixf = A(:,1);
i = i+1; end
end data(:,ifi) = A(:,6);
fclose(f1); clear A;
end
[X,Y] = meshgrid(mixf, times);
surf(X,Y,data');
23
β PDF Example
• The beta-PDF represents
the extent of mixing
between two pure streams
in turbulent flows.
• These streams are often
fuel and oxidizer.
• For segregated streams,
two delta functions result.
• For perfect mixing, one
delta function exists.
• In between, a range of
states exists
24
β PDF Example
25
Summary
• Matlab provides a wealth of functionality for small to
intermediate size projects
• Open source variants available
• Advanced visualization capabilities.
• Highly extensible
• Relatively simple syntax. (a higher level language).
• Extensible, object oriented.
• Many toolboxes available for more advanced, problem
specific work
• Search the web for more tutorials, books, examples