You are on page 1of 28

Matlab Tutorial

Zhen Xu
SUNY at Buffalo
zxu8@buffalo.edu

September 8, 2014

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

1 / 28

Overview

Introduction to Matlab
Basic Matrix Operation
Plotting
Matlab Programming

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

2 / 28

Introduction to Matlab

What is Matlab?
MATLAB is a numerical computing environment. It allows matrix
manipulations, plotting of functions and data, implementation of
algorithms, etc.

The difference between Matlab and C


Matlab is a scripting and mathematical language processor for
working with mathematical equations.
C is a structured programming language for writing programs.

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

3 / 28

The advantages of Matlab

Its basic data element is the matrix. Several mathematical operations


that work on arrays or matrices are built-in to the Matlab
environment.
Vectorized operations. Adding two arrays together needs only one
command, instead of a for or while loop.
The graphical output is optimized for interaction. You can plot your
data very easily, and then change colors, sizes, scales, etc.
Matlabs functionality can be greatly expanded by the addition of
toolboxes.

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

4 / 28

The disadvantages of Matlab

It uses a large amount of memory and on slow computers it is very


hard to use.
It sits on top of Windows, getting as much CPU time as Windows
allows it to have. This makes real-time applications very complicated.

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

5 / 28

Introduction to Matlab
Where to access
Library PC
CSE department Linux
CSE IT Service: https://wiki.cse.buffalo.edu/services/content/matlab

Desktop Tools
Command Window
type commands
Workspace
view program variables, double click on a variable to see it in the
Array Editor
Command History
Semicolon suppress echo
Up-arrow and down-arrow keys
Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

6 / 28

Overview

Introduction to Matlab
Basic Matrix Operation
Plotting
Matlab Programming

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

7 / 28

Basic Matrix Operation

Scalar: a = 1;
Row Vector: b = [1 2];
Column Vector: c = [1; 2];
2*2 Matrix: d = [1 2; 3 4];
Matrix Transpose: e = d;
Matrix Product: f = d*e;
Matrix inverse: g = inv(d);
Matrix Element-by-element Product: h = d.*d;

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

8 / 28

Element Operation

X(1,2) retrieves element at row 1, col 2.


X(2,:) retrieves row 2, all columns.
X(1:2,5:10) retrieves row 1 to 2, col 5 to 10.
Tips: MATLAB is not zero indexed!

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

9 / 28

Matrix Generation

ones(a,b) a * b matrix of all ones.


zeros(a,b) a * b matrix of all zeros.
eye(a,b) a * b identity matrix.
rand(a,b) - a * b matrix of uniformly distributed random numbers on
(0, 1).
randn(a,b) - a * b matrix of normally distributed random numbers
with parameters = 0, = 1.
linspace(a,b,n) - linear spacing from a to b, with n spacings.

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

10 / 28

Important Functions
1

function sum()
B = sum(A)
B = sum(A,dim)
dim = 1[2] implies column sum[row] sum

function find()
ind = find(X > 4)
X > 4 is the relational expression
index = find(X > 4)
Note: X(index) will give the found values.
[row , col] = find(X, ...)

function sort()
[B, index] = sort(A,dim,mode)
dim = 1[2] implies column[row]-wise sorting
mode is either ascending (default) or descending

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

11 / 28

Important Functions
1

function fliplr()
Flip matrix left to right
A = fliplr(A);

function flipup()
Flip matrix up to down
A = flipud(A);

function horzcat()
Concatenate arrays horizontally C = horzcat(A1, A2, ...);

function vertcat()
Concatenate arrays vertically C = vertcat(A1, A2, ...);

function repmat()
Replicate and tile array
B = repmat(A,m,n) creates a large matrix B consisting of an m-by-n
tiling of copies of A

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

12 / 28

Important Functions
1

function reshape()
Reshape array
B = reshape(A,m,n) returns the m-by-n matrix B whose elements are
taken column-wise from A

function randperm()
Randomize numbers
p = randperm(n) returns a random permutation of the integers 1:n

function size()
The size of matrix
[m, n] = size(X) returns the size of matrix X in separate variables m
and n.

function max()
Largest elements
C = max(A) returns the largest elements along different dimensions of
an array.

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

13 / 28

Overview

Introduction to Matlab
Basic Matrix Operation
Plotting
Matlab Programming

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

14 / 28

Basics of Plotting

2D graphing - plot(x,y)
Example:
x = 0 : pi/100 : 2*pi;
y = sin(x);
plot(x, y)
Multiple graphs:
y2=sin(x+pi/2);
plot(x, y, x, y2)

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

15 / 28

Basics of Plotting

Old plot got overwritten - To open a new graph, type Figure


Multiple data sets:
Type hold on to add new plot to current graph
Type hold off to resume overwriting
Edit your Figures:
title(Sine function)
xlabel(x = 0 . . . 2*pi)
ylabel(Sine of x)
Multiple plots in one figure: use subplot(m,n,p)

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

16 / 28

Plotting Example
Example:
x = linspace(0,2*pi,100);
y1 = sin(x);
y2 = x;
y3 = x - (x. 3)/6+(x. 5)/120;
hold on
plot(x,y1);
plot(x,y2,);
plot(x,y3,go);
axis([0 5 -1 5]);
hold off
xlabel(t)
ylabel(approxs. of sin(t))
title(Fun with sin(t))
legend(sin(t),linear, 5th order)
Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

17 / 28

Basics of Ez-Plotting

ezplot(fun) - plots the expression fun(x) over the default domain


2 < x < 2, fun can be a function
ezplot(fun,[min,max]) - plots fun(x) over the domain: min < x < max
Example:
Plot x 2 - y over domain [2, 2]
ezplot(x2-y)
We can zoom in too! ezplot(x2-y,[-3 3 10 0.5])
Note: x2-y is just a string

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

18 / 28

3D Plotting

[X , Y ] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv to


produce a full grid.
surf(X,Y,Z) creates a three-dimensional shaded surface from the z
components in matrix Z, while X and Y are vectors or matrices
defining the x and y components of a surface.
rotate3d on enables mouse-base rotation on all axes within the
current figure.

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

19 / 28

Concrete Examples of Coding Equations and Plotting


Equation: z = (x 2 y 2 ) e (x

2 y 2 )

Code: z=(x.2-y.2).*exp(-x.2-y.2);
Plot: [x,y]=meshgrid(-3:0.3:3);
z=(x.2-y.2).*exp(-x.2-y.2);
surf(x,y,z);
Beautify the output:
surf(x,y,z,...
FaceColor,interp,...
EdgeColor,none, ...
FaceLighting,phong);
camlight left
rotate3d on

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

20 / 28

Overview

Introduction to Matlab
Basic Matrix Operation
Plotting
Matlab Programming

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

21 / 28

Looping
While loop
num = 1; i = 0;
while ( num < 101 )
i = i + num;
num = num + 1;
end
fprintf(the sum from 1 to 100 is %d\n,i);
For loop
i = 0;
for num = 1:100
i = i + num;
end
fprintf(the sum from 1 to 100 is %d\n,i);
Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

22 / 28

Conditionals
If-elseif
v = [ 1 2 3 4 5 6 7 8 9 10];
for i = 1:length(v)
if (v (i) > 5)
% do something
elseif (v (i) > 0) & (v (i) <= 4.9)
% do something
elseif (v (i) == 0)
break; % yes! you can use a break statement
else
% do some other thing
end
end

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

23 / 28

Conditionals

switch-case
method = Bilinear
switch lower(method)
case {linear,bilinear}
disp(Method is linear)
case cubic
disp(Method is cubic)
case nearest
disp(Method is nearest)
otherwise
disp(Unknown method.)
end

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

24 / 28

The M Files
Scripting
M-files are used for Scripts - Scripting lets us run Matlab commands
in batch mode
Scripting also provides us with an easy way to edit Matlab commands

.m Script files
File containing sequence of Matlab commands to perform an action
Invoke from within MATLAB by typing the name of the file, without
extension
Create files with Matlab editor (edit)
Start with a comment line % (same as // comment in C, Java)
No /* block comments */
Matlab scripts are analogous to shell scripts.
Matlabs script (.m) files are platform independent
Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

25 / 28

Writing functions
M-files also used for Functions
Function m-files have local variables and always start with:
function [y, z] = myfunction(a, b)
y = a + b; z = a - b;
The file is saved with the function name and the usual Matlab script
file extension, .m.
the above example is saved as myfunction.m
A MATLAB function may be called from the command line or from
any other M-file
Can return more than one variables:
Matlab functions are analogous to all higher level language functions
We can define auxilliary functions at the end primary function
definition
Matlabs function (.m) files are platform independent
Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

26 / 28

Data storage and retrieval

Mat-files : Used for storing and retrieving data in the form of


matrices or structures
save data.mat X
saves data in variable X as binary .mat file named data.mat
save data.txt X -ascii
saves data in variable X as ascii text file name data.txt
data = load(data.mat); or
X = load(<complete-path-to-datafile>);
Matlabs data (.mat) files are *NOT* platform independent

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

27 / 28

Matlab Documentation

It is impossible to cover all Matlab functions in one class. So keep


practicing.
Online reference:
http://www.mathworks.cn/cn/help/matlab/index.html

Zhen Xu (SUNY at Buffalo)

Matlab Tutorial

September 8, 2014

28 / 28

You might also like