0% found this document useful (0 votes)
56 views

Mat Lab Tutorial

This document provides an introduction to MATLAB and covers downloading and installing MATLAB, navigating the main MATLAB windows, useful commands, online help resources, basic operations on arrays and matrices, symbolic computation, anonymous functions, function files, and script files. It explains how to download MATLAB for free as a Caltech student, sign up for VPN access to use MATLAB off campus, and introduces the main windows in MATLAB including the command window, workspace, command history, figure window, and editor window.

Uploaded by

Mouhamadou Diaby
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Mat Lab Tutorial

This document provides an introduction to MATLAB and covers downloading and installing MATLAB, navigating the main MATLAB windows, useful commands, online help resources, basic operations on arrays and matrices, symbolic computation, anonymous functions, function files, and script files. It explains how to download MATLAB for free as a Caltech student, sign up for VPN access to use MATLAB off campus, and introduces the main windows in MATLAB including the command window, workspace, command history, figure window, and editor window.

Uploaded by

Mouhamadou Diaby
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

ChE 101: Introduction 

to MATLAB



Amy Proctor



January 7, 2012





Downloading MATLAB

MATLAB is available for free for Caltech students and


staff! (However, you need to be on the Caltech network to
use the program.)

To download MATLAB, log into
http://software.caltech.edu and enter your IMSS user
name and password. Click on Start Shopping.''

MATLAB can be found under MathWorks, Inc heading.
Download the latest version of MATLAB.

Using MATLAB off campus

Sign up for VPN at
http://www.imss.caltech.edu/help/vpn-signup-form

Download the Caltech VPN (AnyConnect) client at
https://vpn.caltech.edu/+CSCOE+/logon.html

When you are off the Caltech network, log in before
trying to open MATLAB.

Note: This is not necessary if you download the license file
properly on your computer, but you should sign up for VPN
access on the off chance you need to read a paper or get on
the course website off campus

Main MATLAB windows

Command window: The main window where


MATLAB puts you when you launch the application

Characterized by the >> command prompt)

All commands, including those for running programs
you write, are typed in this window

Workspace pane: Lists all of the variables you have
generated so far, along with their size and type.

Main MATLAB windows

Command history window: All commands typed


on the MATLAB prompt get recorded here (including
those from previous sessions)

Figure window: The output of all graphics commands
typed in the command window goes here

Editor window: Window where you write, edit,
create, and save your own programs in files called m-files
(standard ASCII text files).

Main MATLAB windows

I made some videos to illustrate a few points in


the tutorials. This is the first of them.



Video: http://youtu.be/X40TSdR-sFg

Note that the apostrophe characters
surrounding strings in the font I used for
MATLAB commands/inputs will not copy-paste
properly into MATLAB! 

Correct them before executing commands or
scripts!

Useful commands to know

who lists variables currently in the workspace



clear clears the workspace and removes all variables

clear x y z clears only the variables x, y, and z

clear all clears all variables and functions from the
workspace

mlock fun locks the function fun so that clear cannot
remove it

Useful commands to know

munlock fun unlocks the function fun so that clear can


remove it

clc clears the command window and moves the cursor to
the top

cfc clears the figure window

quit and exit both quit MATLAB

Control-C kills the current command execution (good for
aborting infinite loops)

Online help

MATLAB provides extensive online documentation:


http://www.mathworks.com/help/techdoc/

Typing lookfor, help, helpwin, and helpdesk in the
command window all provide online help

Online help

help lists topics on which help is available



helpwin opens the interactive help window

helpdesk opens the web browser-based help facility

help topic provides help on topic

look for string lists help topics containing string

demo runs the demo program

Operations

+ (addition), - (subtraction), * (multiplication), /


(division), and ^ (exponentiation) work as expected for
numbers

exp(x), sin(x), log(x), cos(x), etc. also work as
expected for numbers

Use ; to suppress screen output (not necessary but
excessive printing may slow down program)

Creating and working with arrays

x = [1 2 3] or x = 1:3 creates a row vector with


three elements

y = [4; 5; 6] or y = (4:6) creates a column vector
with three elements

A=[1 2 3; 4 5 6] creates a 2x3 matrix

You can add or subtract two vectors of the same size
using + or -
Creating and working with arrays

To multiply or divide elements of two same-sized


vectors term by term use the array operators .* or ./
For normal matrix multiplication or multiplying a matrix
by a scalar, no dot is needed before *
You can raise each element of a matrix to a power using
the array operator .^
Trigonometric functions and elementary math functions
operate on vectors term-by-term

Creating and working with arrays

linspace(a, b, c) creates a vectors with c linearly


spaced elements between a and c

linspace(a, b) creates a vectors with 100 linearly
spaced elements between a and c

x:y creates a row vector [x x+1...z], where z is the
largest x+c (c is an integer) less than or equal to y
x:y:z creates a row vector [x x+y x+2y ... q], where
q is the largest x+cy (c is an integer) less than or equal
to z
Creating and working with arrays

zeros(n) or ones(n) creates an n-by-n matrix of


zeros or ones

zeros(m, n) or ones(m, n) creates an m-by-n
matrix of zeros or ones

For a vector x, length(x) gives the number of
elements

For a matrix M, length(M) gives the number of
columns and size(M) returns a row vector [(# of
rows) (# of columns)]
Creating and working with arrays

For a vector x, x(i) gives the ith element of the vector



For a matrix M, x(i, j) gives element in row i and
column j
For a vector x, max(x), min(x), mean(x), and
sum(x) all work as expected

For a matrix M, max(M), min(M), mean(M),
and sum(M) all return row vectors with values for
each column of the matrix

Creating and working with arrays

find(X) locates all nonzero elements of an array X and
returns the linear indices of those elements.

Can use a relational expressions like X > n to obtain
all elements greater than n, etc.

MATLAB stores arrays as a column of elements

The index in that column is the linear index j

X(j) gives the element of X with linear index j, and
X(end) gives the last element in the lower right
hand corner

Symbolic computation

To declare x and y symbolic variables, type in syms x y


Now you can write expressions such as f = (x + y)^2

Use expand(f) or simplify(f) to multiply out or
factor algebraic or trigonometric expressions

subs(f, x, 5) will substitute 5 for x and will return
(5 + y)^2

subs(f, [x, y], [1, 2]) will substitute 1 for x and
2 for y and return 9
Symbolic computation

diff(f, x) will return the derivative of f with respect to


x
diff(f, x, n) will return the nth derivative of f with
respect to x

int(f, x) will return the indefinite integral of f with
respect to x
int(f, x, a, b) integrates f with respect to x from a to
b
Symbolic computation

solve(x^4 + 1) and solve( x^4 + 1 ) return the


symbolic array of x values that satisfy x^4 + 1 = 0

Use the double command [ex: double(solve
(x^4+1))] to return an array of numbers

To solve for equality relations, use a string

Example: solve( x^4 + 1 = x^3 )

Specify the variable [ex: solve(a*x^2 + b*x + c, a)]
when you are using multiple symbolic variables

Anonymous functions

Anonymous functions (functions without names),
which are created and referred to by their handles,
can be created by the command f = @(input list)
mathematical expression

Example: g = @(x, y, z) x^2*y/z creates a
function g(x, y, z)
g(1, 2, 3) will evaluate the function

Function files

A function file begins with a function definition line:
function [output variables] = function_name
(input variables)
The function name must be the same as the file name,
and square brackets are not required for a single-output
variable

Comment lines should start with a % sign

All comment lines immediately after a function definition
line be displayed by MATLAB if help is sought on the
function (similar to a docstring in Python)

Function file example

function [sum, average] = myfun(a, b, c)


% Finds the average of three numbers a, b, and % c
sum = a + b + c;
average = sum / 3;
% Note that input variable names given in the %
function definition line are local to the
% function, so other variable names and
% values can be used in the function call
Executing a function file

To execute a function file, we go to the command window (or


use it in a script file) and type something like:



[x y] = myfun(1, 4, 5);


Then the variable x will be defined as the sum of 1, 4, and 5
(10), and the variable y will be the average of 1, 4, and 5
(10/3)

Executing a function file



If you nest functions, you must end each function



function [x, y] = main(a, b, c)
...
function x = nest1(a, b)
...
function y = nest2(c)
...
end
end
end




Executing a function file

Otherwise functions do not require end (although if you use


it for one function in a file, you must use it for all of them)



A function file may contain multiple functions, but all
functions written below the first function will be treated as
subfunctions and will not be available outside of the file



Script files

A script file is an m-file that does not begin with a
function definition line (does not take arguments) and
contains a set of commands
A script file is run by typing the name of the file (without
the .m extension) on the command line

Script files work on global variables (variables currently
present in the workspace) and variables from the script
are left in the workspace

Never name a script file the same as a global variable
since MATLAB first searches the workspace before
looking for functions

For loops







A for loop is used to repeat a statement or group of
statements for a fixed number of times



Unlike Python, MATLAB does not require a : but does require
that you use an end to end each for loop



Example:

% Find the sum of a vector s elements using a loop instead of the
% built-in sum command
x = [1 2 3 7 8 19 35 2];
sum = 0;
for i=1:length(x)
sum = sum + x(i)
end
Relational operators

MATLAB uses the following relational operators, which
compare the elements of arrays A and B elementwise (or
compare scalars A and B):

Less than: A < B or lt(A, B)

Greater than: A > B or gt(A, B)

Less than or equal to: A <= B or le(A, B)

Greater than or equal to: A >= B or ge(A, B)

Equal: A == B or eq(A, B)

Not equal: A ~= B or ne(A, B)
Logical operators

&, |, and ~ are the logical array operators AND, OR,


and NOT in MATLAB, which compare the elements of
arrays A and B elementwise (or compare scalars A and
B)

However, &&, ||, and ~ are used as the logical
operators AND, OR, and NOT in MATLAB loops!



While loops







A while loop is used to execute a statement or group of
statements until the condition specified by while is no longer
satisfied



Does not require a : but does require an end



Example:

% Find all the powers of 2 below 1000
v = 1; num = 1; i =1;
while num < 1000
v = [v; num];
i = i + 1;
num = 2^i
end
v


If loops







if-elseif-else statements can be used in MATLAB.



Requires an end for the if statement only!



Example:

i = [5, 10, 20, 3, 1]; j = [-1, 3, 6, 7, 2];
num = 0;
for k=l:length(i)
if le(i(k),4) && lt(j, 2)
num = num + 1;
elseif ge(j, 6)
num = num + 2;
else
num = num + 3;
end
end
Making 2-D plots

The most basic command for plotting in 2-D is plot(x, y,
style-option )

x and y are vectors containing the x- and y-
coordinates of points for a graph

style-option is an optional argument

Can change color ( y for yellow, m for magenta,
c for cyan, r for red, g for green, b for blue,
w for white, and k for black)

or change line style ( - for solid, -- for dashed, :
for dotted, -. for dash-dot, and none for no line)

Making 2-D plots

or the marker style for individual data points ( +
for plus sign, o for circle, * for asterisk, x for x-
mark, . for point, ^ for triangle, s for square, d
for diamond, etc.)

Style options can be combined!

Example: plot(x, y, b-- ) will give a blue dashed line
(no point markers)

Example: plot(x, y, c*-- ) gives a cyan dashed line
connecting cyan asterisk points

Example: plot(x, y, + ) gives unconnected blue
(default color) points marked by plus signs

Making 2-D plots

The axis command can be used to change the axes
commands after a plot is generated in a script

General form: axis([xmin xmax ymin ymax])

Can control only part of the axes limits and let
MATLAB set the other limits automatically by
specifying the desired limits in the axis command
and using inf (or -inf) as the values of the limits
that you would like to be set automatically

axis( equal ) sets equal scale on both axes



Making 2-D plots

xlabel(Your label here )labels the x-axis



ylabel( Your label here ) labels the y-axis

title( Your title here ) titles the plot

Use legend(string1, string2, ...) to produce a
legend using the text in string1, string2, etc. as labels

See
http://www.mathworks.com/help/techdoc/ref/
legend.html for legend s many optional arguments

Making 2-D plots

Multiple data sets can be plotted in one graph

plot(x1, y1, style-option , x2, y2, style-
option , etc.) will plot y1 vs. x1 with whatever style
option is indicated (can be left out) and plot y2 vs. x2
with whatever style option is indicated (can be left out),
etc.

The hold command can also be used to overlay plots

Useful when you are generating plottable data in a for
or if loop

Making 2-D plots

% For i from 1 to 5, plot the function y = ix if i is even or the function y = x/i if i is
% odd for x from 1 to 10. Plot even i functions in red and odd i functions in green.
% Overlay the plots.

x = 1:0.1:10;
for i=1:5
if mod(i, 2) == 0
y = i * x
plot(x, y, r )
hold on
else
y = 1/i * x
plot(x, y, b )
hold on
end
end
xlabel( x )
ylabel( y )
title( Plot example )
hold off


Ordinary differential equations

MATLAB has several built-in functions to solve ODEs

General form: [t, y] = solver(ode_function, tspan, x0,
options)

solver is the ODE solver of choice

ode_function is the name of a user-defined function
containing ODEs you want to solve

tspan is a vector of the form [t0 tfinal]
x0 is the initial condition

options are created using odeset
Ordinary differential equations

The ODE function must be written as a system/array of


first-order equations, so you may need to introduce new
variables and recast the original equations in terms of first
order ODEs in the new variables

Two of the most common are ode23 and ode45, which
are both nonstiff solvers

A stiff equation is a differential equation for which certain
numerical methods for solving the equation are
numerically unstable

Ordinary differential equations

ode15s is a stiff solver based on a variable order method
you can try if you think your equations are stiff
ode23 and ode45 implement second-/third-order and
fourth-/fifth-order Runge-Kutta methods, respectively

ode23 is generally quicker but less accurate than ode45

As a rule of thumb, use ode45 since it should give you
good results for most problems

odefile is a help file that can help you with the syntax for
your ODE functions

Example 1: x = x + t, x(0) = 0

xdot = @(x, t) x + t;
tspan = [0 10];
x0 = 0;
[t, x] = ode45(xdot, tspan, x0);
plot(t, x);
xlabel( Time )
ylabel( x )
Example 2: Coupled ODEs

options=odeset('RelTol',1e-6);
ode_system = @(t, x)[-x(1)-x(2);x(1)-2*x(2)];
[t,x] = ode45(ode_system, [0 5], [1; 1], options);
plot(t, x(:,1), t, x(:,2))
l = legend('x_1', 'x_2');
set(l, 'location', 'EastOutside')
xlabel('Time')
ylabel('x_1 and x_2')

Solving a system of nonlinear
equations with fsolve
[x, fval] = fsolve(fun, x0, options) (fval and options
are optional arguments) solves the problem fun(x) = 0

Starts at x0, a vector of initial guesses for the solution to


the nonlinear system

Tries to solve the equations described in the user-written


function fun with the optimization options specified in
the structure options (set using optimset)

Returns a vector of improved guesses x and the values of


the objective function fval given the guesses in x
fsolve example

F = @(x)[2*x(1) - x(2) - exp(-x(1));
-x(1) + 2*x(2) - exp(-x(2))];
x0 = [-5; -5];
options=optimset('Display','off');
[x,fval] = fsolve(F,x0,options)

x= fval =

0.5671 1.0e-06 *
0.5671
-0.4059
-0.4059
Fitting data using the curve fitting
toolbox cftool

Video: http://youtu.be/O2X1lw_bzPY

Curve fitting functions

yy = spline(x, Y, xx) uses a cubic spline interpolation
to find yy, the values of the underlying function Y at the
values of the interpolant xx

Cubic splines fit separate cubic polynomials between
successive data points by matching the slopes and the
curvature of each segment at the data points

beta = nlinfit(X, y, fun, beta0) returns a vector beta
of coefficient estimates for a nonlinear regression of the
responses in y on the predictors in X using the model
specified by fun.

Creating Graphical User
Interfaces (GUIs) using guide

Video: http://youtu.be/u06LwtHIh6Q

I hope this guide helps you get
started in MATLAB. 

Feel free to talk to me or Arvind
about any issues you encounter
(but try online help first!)

You might also like