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

Introduction To MATLAB

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

Introduction To MATLAB

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

Introduction to MATLAB

14:332:347:C2 Signals and Systems Lab 1


Workspace
1-Working Environments: Current
Directory

Editor Window

Command
History

Command
Window

14:332:347:C2 Signals and Systems Lab 2


2-Getting Started
• Simple Arithmetic Operations:
Addition: 3+5 ans=8 %Addition
Subtraction: 5-3 ans=2 %Subtraction
Multiplication: 3*5 ans=15 %Multiplication
Division: 4/2 ans=2 %Division
Power: 2^2 ans=4 %Power
• Comments:
Note above the symbol ‘%’. The symbol ‘%’ is used to insert comments.
Anything written to the right of ‘%’ is considered comment and is not taken
into account from MATLAB.

14:332:347:C2 Signals and Systems Lab 3


2-Getting Started
• The Variable ans:
The symbol ans is a variable. By default, the result of the last executed MATLAB command
is assigned to the variable ans.
• Priority of Operations:
1. Parenthesis
2. Power
3. Multiplication/Division
4. Addition/Subtraction
Examples:
3+7*2 ans =17 %The multiplication is executed before
the addition.
2^2+2*(3-2*(1+14/7)) ans =-2 %The priority is specified from the
parentheses.

14:332:347:C2 Signals and Systems Lab 4


2-Getting Started
• Constants:
pi ans =3.1416 𝜋
i or j ans =0 + 1.0000i Imaginary unit vector for complex numbers
inf ans = Inf ∞
-inf ans = -Inf −∞
eps ans=2.2204e-16 This is the highest accuracy in which the result
of an operation can be calculated.
NaN ans = NaN Unidentified number (not a number).
realmax ans = 1.7977e+308 Largest positive floating point number defined
in MATLAB.
realmin ans = 2.2251e-308 Smallest positive floating point number
defined in MATLAB.

14:332:347:C2 Signals and Systems Lab 5


2-Getting Started
• Useful Built-in Function:
sqrt(2) ans = 1.4142 Square root.
abs(4) ans = 4 Absolute value.
sign(3) ans = 1 The function sign returns 1 if the input number is positive, 0 ifthe input is
zero, and 1 if the input is negative.
exp(1) ans = 2.7183 Exponential.
log(1) ans = 0 Natural logarithm.
log10(100) ans = 2 Base 10 logarithm.
log2(4) ans = 2 Base 2 logarithm.
sin(pi/2) ans = 1 Sine (input argument should be in radian).
cos(pi) ans = -1 Cosine (input argument should be in radian).
tan(pi/4) ans = 1 Tangent (input argument should be in radian).
ceil(0.6) ans = 1 Rounding toward the closer larger integer.
floor(0.6) ans = 0 Rounding toward the closer smaller integer.
round(0.6) ans = 1 Rounding toward the closer integer.

14:332:347:C2 Signals and Systems Lab 6


2- Getting Started
• At MATLAB, a variable can have any name as long as it does not start with a number and it does not include spaces or special characters.
• There is a distinction between capital and small letters.

Example:
Compute sin 45𝑜 2
+ cos 45𝑜 2

Command Result Comment


theta= 45*pi/180 theta=.7854 convert theta from degree to radian
a=sin(theta) a = 0.7071 store the value of sin(theta) in the
variable a
b=cos(theta) b = 0.7071 store the value of cos(theta) in the
variable b
c=a^2+b^2 c=1.0000 store the final value in the variable c
• You can always suppress the output by using (;) at the end of the command
Example
c = a^2+b^2; Nothing will be distplayed in the command window
c c=1

14:332:347:C2 Signals and Systems Lab 7


2- Getting Started
The assigned variables will be shown in the
workspace.

The command “save” is used to save the workspace.


The command “load” is used to load a previously saved workspace.
The command “clear” is used to delete the assigned variables in the workspace

14:332:347:C2 Signals and Systems Lab 8


3- Vectors
• Row Vectors:
• The elements of the vector are given into square brackets [ . . . ], with space
or comma between the elements.
• The index numbering starts from 1.
• In order to refer to a position in a vector, parentheses are used.
Example:
a=[1 2 3 4 5] a= 1 2 3 4 5
a(1) ans = 1
a(0) Subscript indices must either be real positive integers
or logicals.

14:332:347:C2 Signals and Systems Lab 9


3- Vectors
• The command “length()” is used to find the number of elements in a
vector.
• Editing only one specific element of a vector is done by referring to
the position (index) of the vector.
Example:
a a=1 2 3 4 5
length(a) ans = 5
a(3)=13 a = 1 2 13 4 5

14:332:347:C2 Signals and Systems Lab 10


3- Vectors
• Colon operator “:” can be used to define a row vector.
• the syntax “a = First element : Step : Last element”
• The step can be negative, decimal, or even irrational number
Example:
a = 1 : 2 : 11 a = 1 3 5 7 9 11
B = 0 : 0.2 : 1 b = 0 0.2 0.4 0.6 0.8 1
t = 0:pi/3:pi t = 0 1.0472 2.0944 3.1416

14:332:347:C2 Signals and Systems Lab 11


3- Vectors
• Vector Operations (element-wise operations)
If 𝑎 = [𝑎1 𝑎2 … . 𝑎𝑁 ] and 𝑏 = [𝑏1 𝑏2 … . . 𝑏𝑁 ], then:
1- 𝑎 + 𝑏 = [𝑎1 + 𝑏1 𝑎2 + 𝑏2 … . 𝑎𝑁 + 𝑏𝑛 ]
2- 𝑎 − 𝑏 = 𝑎1 − 𝑏1 𝑎2 − 𝑏2 … . 𝑎𝑁 − 𝑏𝑛
3- 𝑎.∗ 𝑏 = [𝑎1 ∗ 𝑏1 𝑎2 ∗ 𝑏2 … . 𝑎𝑁 ∗ 𝑏𝑛 ]
4- 𝑎./𝑏 = [𝑎1 /𝑏1 𝑎2 /𝑏2 … . 𝑎𝑁 /𝑏𝑛 ]
5- a . ^k = [𝑎1𝑘 𝑎2𝑘 … . 𝑎𝑁 𝑘
]
6- k.^a= [𝑘 𝑎2 𝑘 𝑎2 … . . 𝑘 𝑎𝑁 ]
𝑏 𝑏
7- a.^b= [𝑎1𝑏1 𝑎22 … . . 𝑎𝑁𝑁 ]
14:332:347:C2 Signals and Systems Lab 12
3- Vectors
• Column Vectors
a=[1;2;3;4] a=
1
2
3
4
a=[1 2 3 4]’ a=
1
2
3
4
length(a) ans = 4

14:332:347:C2 Signals and Systems Lab 13


3- Vectors
• Useful Built-in Functions:
a=[1 2 3 4 5] a= 1 2 3 4 5 Definition of vector a.
S=sum(a) s = 15 Sum of the elements of a.
cs=cumsum(a) cs = 1 3 6 10 15 Cumulative sum.
pr= prod(a) pr = 120 Product of all elements.
d=diff(a) d=1 1 1 1 Difference between two consecutive elements
[m,i]=max(a) m=5 i=5 The largest value in a (m) and its index (i)
[m,i]=min(a) m=1 i=1 The smallest value is a (m) and its index (i)
max(a) ans = 5 only the largest value is returned.
mean(a) ans =3 Mean value of the elements.
median(a) ans =3 Median value of the vector.
sort(a) ans = 1 2 3 4 5 Sorting in ascending order.
sort(a,'descend') ans = 5 4 3 2 1 Sorting in descending order.

14:332:347:C2 Signals and Systems Lab 14


4- Matrices
• Working with Matrices
A=[1 2 3;4 5 6;7 8 9] A= 1 2 3
4 5 6
7 8 9
A=[1 2 3 A= 1 2 3
456 4 5 6
7 8 9] 7 8 9
A = [1:3;4:6;7:9] A= 1 2 3
4 5 6
7 8 9

14:332:347:C2 Signals and Systems Lab 15


4- Matrices
A(1,1) ans = 1
A(3,2) ans = 6
size(A) ans = 3 3
A(:,:) A=1 2 3
4 5 6
7 8 9
A(2,:) ans = 4 5 6
A(:,3) ans = 3
6
9
A(1:2,1:2) ans = 1 2
3 4

14:332:347:C2 Signals and Systems Lab 16


4- Matrices
• Mathematical Operations on Matrices
1- Addition: A + B
2- Subtraction: A - B
3- Multiplication: A*B
4- Inverse: inv(A)
5- Transpose: transpose(A) or A’

14:332:347:C2 Signals and Systems Lab 17


4- Matrices
• Matrix Concatenation
- It is important when working with piece-wise functions
- Two matrices A and B that have the same number or rows can be concatenated in order to create
a new matrix C with the same number of rows
A=[1 2 3; 4 5 6; 7 8 9] A= 1 2 3
4 5 6
7 8 9
B=[1 1; 2 2; 3 3] B= 1 1
2 2
3 3
C = [A B] C= 1 2 3 1 1
4 5 6 2 2
7 8 9 3 3

14:332:347:C2 Signals and Systems Lab 18


4- Matrices
Two matrices A and B that have the same number or columns can be concatenated
if the second matrix B is placed below A in order to create a new matrix C with the
same number of columns.
A=[1 2 3; 4 5 6; 7 8 9] A= 1 2 3
4 5 6
7 8 9
B=[1 1 1; 2 2 2] B= 1 1 1
2 2 2
C = [A ;B] C= 1 2 3
4 5 6
1 1 1
2 2 2
14:332:347:C2 Signals and Systems Lab 19
4- Matrices
• Some Useful Matrices
1- eye(n): Identity matrix of size nxn
2- ones(n,m): Matrix with entries of ‘1’ of size nxm
3- zeros(n,m): Matrix with zero entries of size nxm
4- rand(n,m): Matrix with random entries of size nxm

14:332:347:C2 Signals and Systems Lab 20


5-Plotting with MATLAB
• 2-D Plotting
To plot the function 𝑦(𝑥), follow the steps:
1- Create the vector 𝑎 ≤ 𝑥 ≤ 𝑏
2- Calculate 𝑦 𝑥
3- Use the command “plot(x,y)” to plot the function 𝑦(𝑥)
- 𝑥 and 𝑦 should have the same number of elements
- The function 𝑦(𝑥) will be plotted in the interval [𝑎, 𝑏]

14:332:347:C2 Signals and Systems Lab 21


5-Plotting with MATLAB
Example:
Plot the function 𝑦 𝑥 = 𝑥 2 , −2 ≤ 𝑥 ≤ 2
x= -2 : 2 x = -2 -1 0 1 2
y=x.^2 y= 4 1 0 1 4
4

plot(x,y) 3.5

2.5

1.5

0.5

0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2

14:332:347:C2 Signals and Systems Lab 22


5-Plotting with MATLAB
Example:
Plot the function 𝑦 𝑥 = 𝑥 2 , −2 ≤ 𝑥 ≤ 2
x= -2 : 0.1 : 2;
y=x.^2; 4

plot(x,y)
3.5

2.5

1.5

0.5

0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2

14:332:347:C2 Signals and Systems Lab 23


5-Plotting with MATLAB
• The Command “linspace”
it is quite hard to estimate the number of elements of the vector
defined by the statement x = [-2*pi:0.3:2*pi]
The syntax is:
x = linspace(initial_value,final_value,number_of_elements)
The produced points, that is, the vector elements are equally spaced

14:332:347:C2 Signals and Systems Lab 24


5-Plotting with MATLAB
• Plotting Several Functions in One Figure
plot(x,y1,x,y2,x,y3)
Example:
Plot the functions 𝑦 𝑥 = 𝑥 2 cos 𝑥 , 𝑔 𝑥 = 𝑥 cos(𝑥), and 𝑓 𝑥 =
2𝑥 sin 𝑥 , 0 ≤ 𝑥 ≤ 2𝜋, in the same figure. 40

x = linspace(0,2*pi,100); 30

20

y = (x.^2).*cos(x); 10

g = x.*cos(x); 0

-10

f = (2.^x).*sin(x); -20

plot(x,y,x,g,x,f) -30

-40
0 1 2 3 4 5 6 7

14:332:347:C2 Signals and Systems Lab 25


5-Plotting with MATLAB
• Changing the Color, Line-style, and the marker
x = linspace(0,2*pi,100);
y = (x.^2).*cos(x);
g = x.*cos(x);
f = (2.^x).*sin(x); 40

30

plot(x,y,’k:p’,x,g,’r-o’,x,f,’b-.x) 20

10

-10

-20

-30

-40
0 1 2 3 4 5 6 7

14:332:347:C2 Signals and Systems Lab 26


5-Plotting with MATLAB
Multiple plot can be made on the same figure by using the ‘hold’
command
1

0.8

0.6

0.4

x=linspace(0,2*pi,150); 0.2

-0.2

plot(x,cos(x));
-0.4

-0.6
1
-0.8
0.8
-1

hold on
0 1 2 3 4 5 6 7 0.6

0.4

0.2

plot(x,sin(x)); -0.2

-0.4

-0.6
100

hold off 80

60

40
-0.8

-1
0 1 2 3 4 5 6 7

plot(x,tan(x))
20

-20

-40

-60

-80

-100
0 1 2 3 4 5 6 7

14:332:347:C2 Signals and Systems Lab 27


5-Plotting with MATLAB
• Formatting a figure
- The command “grid on” adds grid lines to the graph
- The command “grid off” adds grid lines to the graph
- Text beside the x-axis and y-axis can be added using the commands
“xlabel” and “ylabel”
- Graph title is inserted by the command “title”.

14:332:347:C2 Signals and Systems Lab 28


5-Plotting with MATLAB 1

0.8

0.6

0.4

Example: 0.2

x=linspace(0,2*pi,150); -0.2

-0.4

plot(x,cos(x),'r*',x,sin(x),'k') -0.6

-0.8
1

0.8
-1
0 1 2 3 4 5 6 7
0.6

0.4

0.2

grid
0

-0.2

Graph of cos(x) and sin(x) -0.4


1
-0.6
0.8
-0.8
0.6
-1
0.4 0 1 2 3 4 5 6 7

xlabel('x-axis')
0.2

y-axis
0

-0.2

ylabel('y-axis') -0.4

-0.6

title('Graph of cos(x) and sin(x)') -0.8

-1
0 1 2 3 4 5 6 7
x-axis

14:332:347:C2 Signals and Systems Lab 29


5-Plotting with MATLAB
• Plotting in Different Figures
- Command ‘figure’ is used to create a new figure, without affecting the
old figures.
- Command ‘subplot’ splits the figure window into 𝑚 × 𝑛 small
subfigures, and makes the 𝑝𝑡ℎ subfigure active.
subplot(m,n,p)

14:332:347:C2 Signals and Systems Lab 30


5-Plotting with MATLAB
x=linspace(0,2*pi,150);
subplot(2,1,1)
plot(x,sin(x))
subplot(2,1,2)
plot(x,cos(x))

14:332:347:C2 Signals and Systems Lab 31


5-Plotting with MATLAB
• Plotting Discrete-Time Functions
The command stem plots the data sequence given in vector f versus
vector n. The graph consists of lines from the x-axis terminated with
circles on the data value. 9

Example: 7

n=-3:3;
6

f=n.^2; 4

stem(n,f) 2

0
-3 -2 -1 0 1 2 3

14:332:347:C2 Signals and Systems Lab 32


6-Logical/Relational Operators
• Relational Operators

14:332:347:C2 Signals and Systems Lab 33


6-Logical/Relational Operators
• Relational Operators

14:332:347:C2 Signals and Systems Lab 34


6-Logical/Relational Operators
• Logical Operators

14:332:347:C2 Signals and Systems Lab 35


7-Control Flow
• if–elseif-else

if condition1
Statements
elseif condition2
Statements
else
Statements
end

14:332:347:C2 Signals and Systems Lab 36


7-Control Flow
• switch-case-otherwise
switch (variable)
case {value1}
Statements
case {value2,value3, . . . }
Statements
otherwise
Statements
end

14:332:347:C2 Signals and Systems Lab 37


7-Control Flow
• The “for” loop
for counter=vector
Statements
end
• The “while” loop
while (condition)
Statements
end

14:332:347:C2 Signals and Systems Lab 38


8-Symbolic Variables
- The use of symbolic variables allows the computation of limits,
integrals, derivatives, etc.
- The commands ‘sym’ and ‘syms’ are used to define the symbolic
variable
Example:
x=sym(‘x’) x=x
a=limit(sin(x)/x,x,0) a=1
F=2*x^2+3*x+4 F=2*x^2+3*x+4

14:332:347:C2 Signals and Systems Lab 39


8-Symbolic Variables
• Differentiation
The command ‘diff()’ is used to differentiate a function defined by symbolic
variable
Example:
syms x t
f=exp(-t)*cos(x);
diff(f,t) ans = -exp(-t)*cos(x)
diff(f,x) ans = -exp(-t)*sin(x)
diff(f,x,2) ans =-exp(-t)*cos(x)

14:332:347:C2 Signals and Systems Lab 40


8-Symbolic Variables
• Integration
The command “int()” is used to find the integral of a function
Examples:
syms x
f=x^2;
int(f,x) ans = x^3/3
int(f,x,-1,1) ans = 2/3

14:332:347:C2 Signals and Systems Lab 41


8-Symbolic Variables
• Summation of a Function
The command symsum computes symbolic summations. The most
convenient syntax is symsum(expresion, index,lower-limit, upper-limit).
Example:
syms k w
f=w^k;
symsum(f,k,0,inf) ans = piecewise([1 <= w, Inf], [abs(w) <
1, - 1/(w - 1) ])

14:332:347:C2 Signals and Systems Lab 42


8-Symbolic Variables
• The command “subs”
- The command “subs” is used to replace one or more variables
(symbolic or numerical) of a symbolic expression with some others
Example: 0.4

syms t y 0.35

0.3

y=t*exp(-t); 0.25

t1=0 : 0.1 : 5; 0.2

0.15

y1=subs(y,t,t1); 0.1

plot(t1,y1) 0.05

0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

14:332:347:C2 Signals and Systems Lab 43


9-Script Files
- Scripts are M-files with MATLAB commands. Their name must have a
.m suffix, namely, is of the form “name.m”.
- Open new script file by going to Editor Tab -> New -> Script (Ctrl+N).
- Save script file: Editor Tab->Save (Ctrl+S).
- Open a saved script file: Editor Tab-> Open.
- Execute codes inside script file: Editor Tab->Run.

14:332:347:C2 Signals and Systems Lab 44


10- User Functions
- Functions defined by the user.
- To Create a function:
- Editor Tab-> new -> function
- Edit the name, input and output arguments.
- Define function body.
- You can call the function from the command window or from any
script file by its name.

14:332:347:C2 Signals and Systems Lab 45


10- User Functions
Example:
Write a function that accepts as input arguments two matrices and returns their sum and their product.

1- First, go to Editor Tab-> new function


function [ output_args ] = Untitled( input_args )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
end
2- Change the name to “oper”.
3- Change input argument to “A,B”, where A: the first matrix, B: the second matrix.
4- Change the output argument to “sum,prod”;
6- Write the code following code in the body of the function.
sum=A+B;
prod=A*B;
7- You have to save the file before using the function, the name of the file should be the same as the function name.

14:332:347:C2 Signals and Systems Lab 46


10- User Functions
The file should look like the following:

function [ sum,prod ] = proc( A,B )


%UNTITLED Summary of this function goes here
% Detailed explanation goes here
sum=A+B;
prod=A*B;
end
8- [Optional] Change the comment lines to describe what this function does.
14:332:347:C2 Signals and Systems Lab 47

You might also like