You are on page 1of 54

Lecture 01

MATLAB Basics

Todays Lesson
Introduction to MATLAB
Variables and Operators
Built-in Functions
Vectors and Matrices
M-files

Introduction
MATLAB (Matrix Laboratory)
Everything in MATLAB is a Matrix
Powerful graphical computation Tool
The MathWorks Inc. (http://www.mathworks.com)
MATLAB 6 (Release 12 and 13)
MATLAB 7 (Release 14) and 7.5

Interpreted language like Pascal


Executed line by line
No object-oriented features
Computations, Algorithm developments,
Modelling, Simulations, Data analysis,
Explorations, Data visualisation, GUI
developments

Workspace

Current Directory

Command History

Command Prompt

Command Window

MATLAB Help
helpdesk : Will open help window
help function : Give information about
the function on the command window
E.g. help sqrt

doc function : Give more information


about the function on the help window
E.g. doc sqrt

Variables and Operators


2+3
ans =
5

Result will be assigned to a variable ans


You can reuse the results
ans + 2
ans =
7

Variables can be defined by the user


No need to initialise like int a = 0
a = 2; b= 5
a*b
ans =
10
You can save, clear and load the variables
save myFile a b (save in myFile.mat)
clear a b
load myFile

MATLAB uses double-precision floating


point numbers (64 bit)
It shows only 5 digits by default
1/3
0.3333
You can change the number of digits
format long (15 digits) -> format short (5 digits)

You can define character variables (16


bits)
x = Hi, How are you.
Variable names
First character should be a letter
Any letter, a number or _
Case sensitive

Built-in variables
i, j (for complex numbers), pi (), ans, Inf
(Infinity), NaN (Not a number)

MATLAB Output
disp () : Print output to the screen
disp(Hi, How are you.)
disp(a)

fprintf () : Can be used with formatting


fprintf(Answer = %2.3f.\n, 3*pi)

Graphical outputs will be displayed in the


Figure window
ezplot(x^2+x)

% is used for Comments


Anything after that is not executed
Improve readability of the program

Semicolon (;) at the end will suppress


the output
A = 12 *2;

clc Clears the command window

Built-in Functions
MATLAB has a library of built-in functions
Sqrt(2), log(), log10(), cos()
floor(), ceil(), abs(), clock, factor()
sum(), prod(), exp(),

Exercise
Which of the following is the best
approximation to the square root of 7
2709/1024
10583/4000
2024/765

Vectors and Matrices


Row Vector
a = [2, 4, 5]
or
a = [2 4 5]

Column Vector
b = [10; 20; 30]

Use transpose operator to convert


a

or

transpose(a)

Indexing Elements
MATLAB indexing starts from 1 not from 0
a = [ 5 3 4] (Square brackets)
a(1) = 5
a(2) = 3
a(3) = 4
(Parenthesis)
A(2:3) = 3 4
A(1:end-1) = 5 3
length (a) Vector Length
min/max(a)
sort(a) : Sort in Ascending order
find (a == 3)
find (a < 3 & a > 6)

a = 1:10

(Array of integers between 1 and 10)

b = 1:2:10 (With increment 2)


Increment could be or a fragment
linspace (start, end, no of points): Can divide a
range into equal spaces
linspace (1, 9, 5)

Matrices
a = [2 3 4; 5 6 7]

(2x3 Matrix)

size (a) Give the dimensions of a Matrix


2
5

3
6

4
7

Concatenating Matrices
A = [10 20]

D = [a b]
E = [a; b]
F = [e c]

b = [30 40]

c = [50; 60]

Create a matrix with zeros


zeros (rows, columns)
zeros(1, 10)

Creates a matrix with 1s


ones (rows, columns)
ones (2, 3)

Creates a matrix with random numbers


(uniformly distributed 0-1)
rand (2, 3)

Element by Element Operations


Use . (dot) with all the Operators
(+, -, /, *, ^ - Exponentiation)
A = [2 5; 4 1]
a.^2
a.*b

=>

[4 25; 16 1]

Exercise
Find a way to delete 0s from a vector

Use clock function to find the number


hours left to the end of this month

M-Files
Scripts can be run with MATLAB

Collection of commands
Executed in sequence
Use MATLAB editor
Save as MATLAB file (Extension .m)

From command prompt


edit abc.m

From MATLAB Desktop


File -> New -> M-File

Click the new file button on the Toolbar

To run the M-File script


Move to the directory where file is saved
Type the file name (without .m extension)
>> cd the directory
>> abc (abc.m file)

Matrices, Program Controls,


User-defined Functions

Vectors and Matrices


Row Vector
a = [2, 4, 5]
or
a = [2 4 5]

Column Vector
b = [10; 20; 30]

Use transpose operator to convert


a

or

transpose(a)

Indexing Elements
MATLAB indexing starts from 1 not from 0
a = [ 5 3 4] (Square brackets)
a(1) = 5
a(2) = 3
a(3) = 4 (Parenthesis)
A(2:3) = 3 4
A(1:end-1) = 5 3

length (a) Vector Length


min(a), max(a), sum(a)
sort(a) : Sort in Ascending order
find (a == 3)

find (a < 3 & a > 6)

a = 1:10

(Array of integers between 1 and 10)

b = 1:2:10 (With increment 2)


Increment could be or a fragment
linspace (start, end, no of points): Can divide a
range into equal spaces
linspace (1, 9, 5)

Matrices
Matrix is a two dimensional array of items
a = [2 3 4; 5 6 7]

(2x3 Matrix)

size (a) Gives the dimensions of a Matrix


2
5

3
6

4
7

Concatenating Matrices
A = [10 20]

D = [a b]
E = [a; b]
F = [e c]

b = [30 40]

c = [50; 60]

Create a matrix with zeros


zeros (rows, columns)
zeros(1, 10)

Creates a matrix with 1s


ones (rows, columns)
ones (2, 3)

Creates a matrix with random numbers


(uniformly distributed 0-1)
rand (2, 3)

Element by Element Operations


Use . (dot) with all the Operators
(+, -, /, *, ^ - Exponentiation)
a = [2 5; 4 1]

b = [5 10; 3 2]

a.^2

=>

[4 25; 16 1]

a.*b

=>

[10 50; 12 2]

Matrix Operations

A matrix can be multiply by any scalar (c)


A
3A
4
6
10 20

=>

3*A

=>

12
30

18
60

If A and B have the same dimensions A+B


and A-B are valid
A
4
10

B
6
20

2
6

A-B
4
8

=>

2
4

2
12

Multiplication of matrices A with


dimensions nxm and B with dimensions mxl
will produce A*B with dimensions nxl
A2x3

B3x1

=>

AB2x1

10

2x10+4x5+3x2

46

5
2

5x10+1x5+2*2

59

Exercise
Use clock function to find the number of
hours left to the end of this month

Conditional Controls
Relational Operators
equal
==
not equal ~=
greater than or equal

>=

Logical Operators
And
Not
All true
0 is false

&
~
all

Or

Any true

any

if-else
Conditional statement will be evaluated for true
or false
if condition
command block 1
else
command block 2
end
elseif can be used for more than one conditions
e. g.

n = 4;
if n > 3
x = A
else
x = B
end

for Loop
Use for a know number of iterations
Loop variable can be sequential or can be
given as a vector
for loop variable = start: end
command block
end
e. g.
for n = 1:100
fprintf (n = %d\n, n);
end

while Loop
Do not know about the number of iterations
while condition
command block
end

Command block is executed while the


condition is true
Careful about infinite loops

switch
Execute one set among several
switch number
case 1
command block 1
case 2
command block 2
|
case n
command block n
end
e. g.

mynumber = input('Enter a number:');


switch mynumber
case 1
disp(Student');
case 2
disp(Staff');
otherwise
disp(Not a valid Option)
end

User-defined Functions
Function must have a functional declaration
function [avg, range] = stats(x)

Outputs

Inputs

Function name should match MATLAB Mfile name

M-file (stats.m)
function [s, r]=stats(x);
s = sum(x)
r = max(x) - min(x)

Command Prompt
>> a = [2 4 1]
>> stats(a)
s=
7
r=
3

Exercise
Write a function to delete 0s from a
vector

2D Graphs
plot() cab be used to draw 2D graphs
plot (x, y, c - *)

Color

Style

Marker

plot (x, y, c - -, LineWidth, 2,


MarkerSize, 10)

x = 0:0.5:20

% x values

y = x.^2+3*x-3

% y values

plot (x, y, c - -)
title(2D Graph)

% Add Title

xlabel(X)

% Add X-axis Label

ylabel(Y)

% Add y-axis label

grid on

% Add Grids

hold on

% Can draw another

plot (x, 300, c . *)

Plot Strings

figure
x = -pi:pi/40:pi
plot(x, cos(x), y-o, x, sin(x), c.-)
h1 = legend (cos_x, sin_x)
set(h1, 'Location', 'NorthWest')
text(2, 0.5, cos(x))

3D Line Plots
time=0:0.001:4*pi;
x=sin(time);
y=cos(time);
z=time;
plot3(x,y,z,'k','LineWidth',2);
zlabel('Time');

Multiple Plots in One Figure


Figure window can be partitioned and
locate the graphs using subplot()
subplot (rows, columns, location)
subplot(2, 2, 1)

subplot(2, 2, 3)

subplot(2, 2, 2)

subplot(2, 2, 4)

x = -pi:pi/40:pi
subplot(1, 3, 1)
plot(x, sin(x))
title (sin)

% First graph

subplot(1, 3, 2)
plot(x, cos(x))
title (cos)

% Second graph

subplot(1, 3, 3)
plot(x, tan(x))
title (tan)

% Third graph

Surface Plotting
[X,Y] = meshgrid (-8:.5:8);
R = sqrt(X.^2 + Y.^2) ;
Z = sin(R)./R;
mesh (X,Y,Z,'EdgeColor','black')
surf (X,Y,Z)
colormap hsv
colorbar

% Has filled colors

Contours
Contours in 2D
[c, h] = contour (X, Y, Z, 20)
Number of Contours

clabel (c, h)
Filled contours
contourf (X, Y, Z, 20)
Contours in 3D
contour3 (X, Y, Z, 20)

% Label the contours

File Input/Output
Data can be entered in a Text File
x , y
2 , 32
6 , 65

Data can be imported to an array


a = importdata(myData.txt, , )
Delimiter
x = a.data(:, 1)
y = a.data(:, 2)

% Extract first column


% Extract second column

Read/Write to Excel
Writing to an Excel File
xlswrite(CK, a.data)
Reading from an Excel File
xlsread(CK.xls)

You might also like