Professional Documents
Culture Documents
Introduction to Matlab
Matlab: Matrix Laboratory
Numerical Computations
with matrices
• Every number can be
represented as matrix
Why Matlab?
• User Friendly (GUI)
• Easy to work with
• Powerful tools for complex mathematics.
C.B. Pham 1
Matlab desktop
Command window
C.B. Pham 2
“Help” in Matlab
>> demo
C.B. Pham 3
2. Matrix operations
Addition Substraction
>> c = a + b >> c = a - b
Multiplication
>> c = a*b % matrix multiplication
>> c = a.*b % element wise multiplication
C.B. Pham 4
Variable: constant, vector, matrix
Real Complex
>> x = 5 >> x = 5 + 10*i
x= x=
5 5.0000 + 10.0000i
Row vector Column vector
>> x = [1, 2, 3] % [1 2 3] >> x = [1; 2; 3]
x= x=
1 2 3 1
2
Matrix 3
>> x = [1 2 3; 4 5 6]
x=
1 2 3
4 5 6 Note: Variable Names are case sensitive
C.B. Pham 5
Vectors
C.B. Pham 6
Matrix
C.B. Pham 7
Matrix
C.B. Pham 8
Accessing matrix elements
>> M = [ 1 2 3 4; 5 6 7 8; 9 10 11 12]
M=
1 2 3 4
5 6 7 8
9 10 11 12
>> x = M(2, 3) % element at row 2 & column 3 of M
x=
>> y = M(2, :) % select the 2nd row M
7
y=
5 6>>7z 8
= M(2:3, 2:3) % select sub-matrix of M
z=
6 7
C.B. Pham
10 11 9
Concatenating, Appending, …
>> A = [ 1 2 3 ] ;
>> B = [ 4 5 6 ] ;
>> R = [ A B ]
R= >> S = [ A; B ]
1 2 3 4 5 6 S= >> S(3, 3) = 7
1 2 3 S=
4 5 6 1 2 3
4 5 6
0 0 7
C.B. Pham 12
More Operators & Functions
>> M = [ 1 2; 5 6 ]
M=
>> sum(M)
1 2
ans =
5 6
6 8
>> sum(ans) % equivalent to sum(sum(M))
ans =
14 >> M’ % equivalent to transpose(M)
ans =
1 5
2 6 >> diag(M) % diagonal elements
ans =
1
C.B. Pham 6 13
More Operators & Functions
C.B. Pham 14
More Operators & Functions
5x 3
• Partial Fraction Expansion x 3 3x 2 4
8 7 8
9 3 9
x 2 ( x 2) 2 x 1
C.B. Pham 16
Continuous time plots - plot
C.B. Pham 17
Discrete time plots - stem
>> x = [ 0 : 0.5 : 10 ];
>> y = x.^2;
>> stem(x, y)
>> grid on
>> xlabel(‘Time, t’)
>> ylabel(‘Speed, s’)
>> title(‘Graph s = t^2’)
C.B. Pham 18
Multiple Data Sets in One Graph
>> p = sin(2*t);
>> v = 2*cos(2*t);
>> plot(t, p)
>> plot(t, v)
>> plotyy(t, p, t, v)
C.B. Pham 20
4. Function in Matlab
• Syntax
function [out1, out2, …] = function_name (in1, in2, …)
…..
….. % commands
• Description:
function [out1, out2, ...] = function_name (in1, in2, ...)
defines function function_name that accepts inputs in1,
in2, etc. and returns outputs out1, out2, etc.
a A = a.b
h
A = a.h / 2
b
C.B. Pham a 22