Introduction to MATLAB
Prepared by: Mahendra Shukla
What is MATLAB
High level language for technical computing
Stands for MATrix LABoratory
Everything is a matrix - easy to do linear algebra
The MATLAB System
Development Environment
Mathematical Function Library
MATLAB language
Application Programming Language
Matlab Screen
Command Window
type commands
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
view past commands
save a whole session
using diary
Variables
No need for types. i.e.,
int a;
double b;
float c;
All variables are created with double precision unless
specified and they are matrices.
Example:
>>x=5;
>>x1=2;
After these statements, the variables are 1x1 matrices
with double precision
Matrices & Vectors
All (almost) entities in MATLAB are matrices
Easy to define:
Use ‘,’ or ‘ ’ to separate row elements -- use ‘;’ to separate rows
>> A = [16 3; 5 10]
A = 16 3
5 10
Matrices & Vectors - II
Order of Matrix - mn
m=no. of rows, n=no. of columns
Vectors - special case
n=1 column vector
m=1 row vector
Creating Vectors and Matrices
Define >> A = [16 3; 5 10]
A = 16 3
5 10
>> B = [3 4 5
6 7 8]
Transpose B = 3 4 5
6 7 8
Matrix:
Vector : >> A=[1 2; 3 4];
>> a=[1 2 3]; >> A'
>> a' ans =
1 1 3
2 2 4
3
Creating Vectors
Create vector with equally spaced intervals
>> x=0:0.5:pi
x =
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
Create vector with n equally spaced intervals
>> x=linspace(0, pi, 7)
x =
0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416
Equal spaced intervals in logarithm space
>> x=logspace(1,2,7)
x =
10.0000 14.6780 21.5443 … 68.1292 100.0000
Note: MATLAB uses pi to represent , uses i or j to represent imaginary
unit
Variables — Scalars, Vectors,
and Matrices
Real scalar >> x = 5
Complex scalar >> x = 5+10j (or >> x = 5+10i)
Row vector >> x = [1 2 3] (or x = [1, 2, 3])
Column vector >> x = [1; 2; 3]
3 × 3matrix >> x = [1 2 3; 4 5 6; 7 8 9]
Caution (Complex elements of a matrix should not be typed
with spaces, i.e., ‘-1+2j’ is fine as a matrix element, ‘-1 + 2j’
is not. Also, ‘-1+2j’ is interpreted correctly whereas ‘-1+j2’ is
not)
Complex scalar >> x = 3+4j
Real part of x >> real(x) ⇒ 3
Imaginary part of x >> imag(x) ⇒ 4
Magnitude of x >> abs(x) ⇒ 5
Angle of x >> angle(x) ⇒ 0.9273
Complex conjugate of x >> conj(x) ⇒ 3 - 4i
Creating Matrices
zeros(m, n): matrix with all zeros
ones(m, n): matrix with all ones.
eye(m, n): the identity matrix
rand(m, n): uniformly distributed
random
randn(m, n): normally distributed
random
magic(m): square matrix whose
elements have the same sum, along
the row, column and diagonal.
Concatenation of Matrices
x = [1 2], y = [4 5], z=[ 0 0]
A = [ x y]
1 2 4 5
B = [x ; y]
1 2
4 5
Matrix operations
^: exponentiation
*: multiplication
/: division
\: left division. The operation A\B is
effectively the same as INV(A)*B,
although left division is calculated
differently and is much quicker.
+: addition
-: subtraction
Array Operations
Evaluated element by element
.' : array transpose (non-conjugated transpose)
.^ : array power
.* : array multiplication
./ : array division
Very different from Matrix operations
>> A=[1 2;3 4]; But:
>> B=[5 6;7 8]; >> A.*B
>> A*B 5 12
19 22 21 32
43 50
Some Built-in functions
mean(A):mean value of a vector
max(A), min (A): maximum and minimum.
sum(A): summation.
sort(A): sorted vector
median(A): median value
std(A): standard deviation.
det(A) : determinant of a square matrix
dot(a,b): dot product of two vectors
Cross(a,b): cross product of two vectors
Inv(A): Inverse of a matrix A
Adding Elements to a Vector or a Matrix
>> A=1:3 >> C=[1 2; 3 4]
A= C=
1 2 3 1 2
>> A(4:6)=5:2:9 3 4
A= >> C(3,:)=[5 6];
1 2 3 5 7 9 C=
1 2
>> B=1:2 3 4
B= 5 6
1 2
>> B(5)=7; >> D=linspace(4,12,3);
B= >> E=[C D’]
1 2 0 0 7 E=
1 2 4
3 4 8
5 6 12
Operators (relational, logical)
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
& And operator
| Or operator
Flow Control
if
for
while
break
….
Graphics - 2D Plots
plot(xdata, ydata,
‘marker_style’);
For example: Gives:
>> x=-5:0.1:5;
>> sqr=x.^2;
>> pl1=plot(x, sqr, 'r:s');
Graphics - Overlay Plots
Use hold on for overlaying graphs
So the following: Gives:
>> hold on;
>> cub=x.^3;
>> pl2=plot(x, cub,'b:o')
Graphics - Annotation
Use title, xlabel, ylabel and legend
for annotation
>> title('Demo plot');
>> xlabel('X Axis');
>> ylabel('Y Axis');
>> legend([pl1, pl2], 'x^2', 'x^3');
Graphics - Annotation
Graphics-Stem()
stem()is to plot discrete sequence data
The usage of stem() is very similar to plot()
cos(n/4)
1
>> n=-10:10;
>> f=stem(n,cos(n*pi/4)) 0.5
>> title('cos(n\pi/4)')
>> xlabel('n') 0
-0.5
-1
-10 -5 0 5 10
n
subplots
Use subplots to divide a plotting window into several panes.
Cosine Sine
1 1
>> x=0:0.1:10; 0.8 0.8
>> f=figure; 0.6 0.6
>> f1=subplot(1,2,1); 0.4 0.4
>> plot(x,cos(x),'r'); 0.2 0.2
>> grid on; 0 0
>> title('Cosine')
-0.2 -0.2
>> f2=subplot(1,2,2);
>> plot(x,sin(x),'d'); -0.4 -0.4
>> grid on; -0.6 -0.6
>> title('Sine'); -0.8 -0.8
-1 -1
0 5 10 0 5 10
Save plots
Use saveas(h,'filename.ext')
to save a figure to a file.
Useful extension types:
bmp: Windows bitmap
>> f=figure;
emf: Enhanced metafile
>> x=-5:0.1:5;
eps: EPS Level 1
>> h=plot(x,cos(2*x+pi/3));
fig: MATLAB figure
>> title('Figure 1');
jpg: JPEG image
>> xlabel('x');
m: MATLAB M-file
>> saveas(h,'figure1.fig')
tif: TIFF image, compressed
>> saveas(h,'figure1.eps')
Sine Wave in Matlab
t = [ 0 : 1 : 40 ]; % Time Samples
f = 500; % Input Signal Frequency
fs = 8000; % Sampling Frequency
x = sin(2*pi*f/fs*t); % Generate Sine
Wave
figure(1);
stem(t,x,'r'); % View the samples
figure(2);
stem(t*1/fs*1000,x,'r'); % View the
samples
hold on;
plot(t*1/fs*1000,x); % Plot Sine Wave
Practice Problems
Plot the following signals in linear scale
x(t ) sin( 3t ) 5 t 5
y (t ) e 2t 3 0t 5
Plot the following signals, use log scale for y-axis
x(t ) et 2 (2t 1) 0 t 10
Plot the real part and imaginary part of the following signal
x(t ) e0.5t j (t / 3) 0 t 10
For the signal in previous question, plot its phase and magnitude