Ilovepdf Merged
Ilovepdf Merged
Experiment No. 1
MATLAB Programming
1. General View
MATLAB (Matrix Laboratory) is a high-level programming language that has been
used extensively to solve engineering and science problems in academic and research
institutions as well as industry.
MATLAB works with three types of windows on your computer screen. These are:
A. The Command window: The command window is the main window in which you
communicate with the MATLAB interpreter. The MATLAB interpreter displays a command
prompt >> indicating that it is ready to accept commands from you. You can use command
window to enter variables and run functions and M-files and controlling input and output data.
You can clear the Command window with the clc.
Say you want to evaluate the expression f where a=1.2, b=2.3, c=4.5 and d=4. Then in the
command window, type:
a =1.2;
b =2.3;
c =4.5;
d =4;
f=a^3+sqrt(b*d)-4*c
ans = -13.2388
B. The Figure window: The Figure window only pops up whenever you plot something.
Figure; plot(a,b,‘x’);
1
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
C. The Editor window: The Editor window is used for writing and editing MATLAB programs
(called M-files) and can be invoked in Windows from the pull-down menu after selecting File |
New | M-file.
Note: the semicolon after each variable assignment. If you omit the semicolon, then MATLAB
echoes back on the screen the variable value.
2. Arithmetic Operations
There are four different arithmetic operators:
+ Addition
− Subtraction
* Multiplication
/ Division (for matrices it also means inversion)
X =[1,3,4]
Y =[4,5,6]
X+Y
ans = 5 8 10
For the vectors X and Y, the operator ‘+’ adds the elements of the vectors, one by one, assuming that
the two vectors have the same dimension.
To compute the dot product of two vectors, you can use the multiplication operator *. For the above
example, it is:
X*Y’
ans = 43
This means (1×4 + 3×5 + 4×6 = 43 ). Note the single quote (’) after Y. The single quote denotes the
transpose of a matrix or a vector.
In MATLAB, most arithmetic operations (+, -, *, /, ^) are designed for matrix operations. However,
when performing element-wise operations, MATLAB provides special operators that work on
corresponding elements of arrays or matrices.
Three Important Element-wise Operators:
1- Element-wise Multiplication (.*). %Multiplies corresponding elements of two arrays.
A = [1 2 3];
B = [4 5 6];
C = A .* B; % Result: [4 10 18].
The ‘.*’ operator in MATLAB is highly recommended because it is significantly faster than using for
loops for element-wise computations.
2
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
2- Element-wise Division (./). %Divides each element of one array by the corresponding element of another.
A = [10 20 30];
B = [2 4 5];
C = A ./ B; % Result: [5 5 6].
3- Element-wise Exponentiation (.^).% Raises each element of an array to the power of the
corresponding element in another array.
3. Complex Numbers
MATLAB supports complex numbers, and the imaginary unit is represented by i or j, provided
that you have not redefined them as variables in your code.
Try the following:
z=3 + 4i
conj(z) % computes the conjugate of z
angle(z) % computes the phase of z
real(z) % computes the real part of z
imag(z) % computes the imaginary part of z
abs(z) % computes the magnitude of z
z1 = 3 + 4i;
z2 = 1 - 2i;
sum_z = z1 + z2; % Addition
prod_z = z1 * z2; % Multiplication
div_z = z1 / z2; % Division
conj_z = conj(z1); % Complex conjugate
abs_z = abs(z1); % Magnitude (modulus)
angle_z = angle(z1); % Phase angle in radians
Note: In MATLAB, you can define the imaginary unit using any variable name, as long as you
explicitly assign it a complex value. Here’s an example:
% Perform operations
sum_z = z1 + z2; % Addition
prod_z = z1 * z2; % Multiplication
abs_z1 = abs(z1); % Magnitude of z1
3
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
D. Array Indexing
In MATLAB, arrays (or vectors) use 1-based indexing, meaning the first element is accessed with
index 1, i.e., y(1), not 0 as in C/C++. Also, MATLAB uses parentheses () for indexing instead of
square brackets [] like in C/C++.
To create an array having as elements the integers 1 through 6, just enter:
Method 1: Using Colon Operator (:)
x= 1:6;
The ‘:’ notation above creates a vector starting from 1 to 6, in steps of 1. If you want to create a
vector from 1 to 6 in steps of, say 2, then type:
x=1:2:6
ans = 1 3 5
In MATLAB, extracting, inserting, and concatenating elements in a vector can be done easily
using parentheses () for indexing and square brackets [] for concatenation.
A = [1 2 3]; % First array
B = [4 5 6]; % Second array
y = [1 2 4 5];
y = [y(1:2) 3 y(3:end)]; % Insert 3 between 2 and 4
4
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
E. Allocating Memory
In MATLAB, you can preallocate memory for a one-dimensional array (vector) using the zeros
command. This is useful for efficiency, especially when dealing with large arrays.
Example: Allocating Memory for a 100-Dimensional Array
y = zeros (100, 1); % Creates a 100×1 column vector filled with zeros
y = ones (1, 100); % 1×100 vector filled with ones
Similarly, you can allocate memory for two-dimensional arrays (matrices). The command
y=zeros(4,5) % defines a 4 * 5 matrix. Similar to the zeros command,
K=find(x)
k=
1
5
7
8
9
Use the logical not operator on x to locate the zeros.
S = find(~x)
Example: Find the elements that are less than 10 in a 4-by-4 magic square matrix.
A = magic(4)
k = find(A<10)
G. Plotting
You can plot arrays using MATLAB’s function plot. The function plot(.) is used to generate line
plots. The function stem(.) is used to generate “picket-fence” type of plots.
x=1:20;
plot(x)
stem(x)
More generally, plot(x,y) plots vector y versus vector x. Various line types, plot symbols and colors
may be obtained using plot(x,y,s) where s is a character string indicating the color of the line, and the
type of line (e.g., dashed, solid, dotted, etc.).
plot(x,y,'--r')
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y,’*g’)
You can insert x-labels, y-labels, and title to the plots, using the functions, xlabel(.), ylabel(.) and
title(.) respectively.
figure; % figure creates a new figure window using default property values
title('Lab exp 1'); %Put a title for the plot
xlabel('trial'); ylabel('distance, ft');%Name for x-axis and y-axis
xlim([-1 10]); ylim([0 6]); %Define the limits for each axis
axis([-1 10 0 6]); %Define the limits for both axis
grid on; %Producing lines for scale divisions(grids)
figure(1); % Opens or activates Figure 1
Create Multiple Figures
plot(1:10, (1:10).^2, 'r'); % Plot in Figure 1
grid on;
figure(2); % Opens or activates Figure 2
plot(1:10, sqrt(1:10), 'b'); % Plot in Figure 2
grid on;
6
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
To plot two or more graphs on the same figure, use the command subplot. For instance, to show the
above two plots in the same figure, type:
x=1:8;
subplot(2,1,1), plot(x)
subplot(2,1,2), stem(x)
The (m,n,p) argument in the subplot command indicates that the figure will be split in m rows and n
columns. The ‘p’ argument takes the values 1, 2 . . . m×n. In the example above, m = 2, n = 1,and p
= 1 for the top figure and p = 2 for the bottom figure.
**** To get more help on plotting, type: help plot or help subplot.
H. Input command
In MATLAB, users can enter data through the keyboard using the input function. This is useful for
interactive scripts where user input is needed.
e.g: z = input('Enter values for z in brackets=');
When executed, the screen displays
Enter values for z in brackets =
Then the user can enter, say, [5.1 6.3 -18] {here we assign row vector with 3 elements to z}
• Since the command does not end with a semicolon (;), MATLAB displays the assigned
values in the Command Window.
• If you add a semicolon, the values will be stored in z but not displayed
I. Display command
In MATLAB, the disp function is used to display values or messages in the Command Window
without printing variable names or extra formatting.
temp = 78;
disp(temp); % Displays the value of temp
disp('Degrees F'); % Displays the text
7
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
8
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
Task: Write a MATLAB script that asks the user to enter a day of the week and then
prints a corresponding message using a switch-case statement.
Example
% find factorial of 4
n = 4; % Initialize n as 4
f = n; % Start f with the value of n (4)
while n > 1 % Continue looping while n is greater than 1
n = n-1; % Decrease n by 1 in each iteration
f = f*n; % Multiply f by the new value of n
end
disp(['n! = ' num2str(f)]) % display numbers as strings
9
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
step-by-Step Execution
Iteration n Before Update n After Update (n= n - 1) f (Updated as f * n)
1st 4 3 4 * 3 = 12
2nd 3 2 12 * 2 = 24
3rd 2 1 24 * 1 = 24
4th 1 (Loop stops) (Final result)
10
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
Experiment No. 2
Generating Fundamental Signals
A. Unit Step
1. Continuous Time Unit Step
It is commonly used in signal processing and control systems to represent
sudden changes, such as turning a system on at t=0. The unit step function
u(t), also known as the Heaviside unit function, is defined as:
1 𝑡≥0
𝑢(𝑡) = {
0 𝑡<0
The unit step function is defined in MATLAB as follows:
t=-10:0.01:10;
1
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
%% shift to left by 3
g=heaviside(t+3);
figure; plot(t,g,'r')
axis([-10 10 -0.5 1.5]);grid on; grid minor
%% shift to right by 4
h=heaviside(t-4);
figure; plot(t,h,'g')
axis([-10 10 -0.5 1.5]);grid on; grid minor
%% folding or time reversal
k=heaviside(-t);
figure; plot(t,k,'b')
axis([-10 10 -0.5 1.5]);grid on; grid minor
In practical applications, we typically focus on the area of the Dirac delta (δ) function
rather than its exact shape. It is commonly represented as a narrow pulse with a width
of 1/Δ and a height of Δ, where Δ approaches zero while maintaining a total area of 1:
∞
∫ 𝛿(𝑡)𝑑𝑡 = 1
−∞
In MATLAB, the delta function is defined similarly and is not directly visible at t=0.
Since the ideal delta function is non-existent in numerical computation, it cannot be
shifted or reversed directly as a standard function. as in the following example:
t= -10:0.01:10;
f= dirac(t);
figure; plot(t,f)
To handle the infinity at t=0, use numeric values instead of symbolic representations.
Replace the Inf value with 1 and plot the Dirac delta function using stem for better
visualization.
3
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
idx = find(f== Inf); %searches for all indices in f where the value is inf
f(idx) = 1; % set Inf to finite value(making the function finite)
figure; plot(t,f);grid on
axis ([-10 10 -0.5 1.5])
4
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
MATLAB's built-in dirac function follows the continuous-time definition, where δ(t)
is treated as a symbolic function with infinite value at t=0.
in discrete-time signals, the Kronecker delta function represents an impulse occurring
at n=0:
1 𝑛=0
𝛿[𝑛] = {
0 𝑛≠0
check that using the following code:
n=-10:10;
f=dirac(n-5); % shift right by 5(continuous-time Dirac delta function)
idx = find(f== Inf); % identifies where the dirac function returns Inf
f(idx) = 1; % set Inf to finite value
figure; stem(n,f);grid on; axis([-10 10 -.5 1.5])
%% shifted impulse
n =-10:10;
impulse = n==2;% same as f=dirac(n-2);
figure; stem(n,impulse); grid on;axis([-10 10 -.5 1.5])
C. Ramp signal
1. Continuous Time Ramp
A ramp signal, denoted as 𝑟(𝑡) , is a piecewise linear function defined as:
𝑡, 𝑡≥0
𝑟(𝑡) = {
0, 𝑡<0
This signal increases linearly with time for 𝑡 ≥ 0 and is zero for 𝑡 < 0. The ramp
signal can be expressed using the unit step function, 𝑢(𝑡)
𝑟(𝑡) = 𝑡. 𝑢(𝑡)
This representation is useful in signal processing, especially when dealing with Laplace
transforms, convolution, and system analysis.
T = -10:0.01:10;
unitstep= t>=0; % generate unit step
5
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
figure;plot(t,unitstep); grid on
axis([-10 10 -.5 1.5])
ramp = t.*unitstep; % multiply t
figure;plot(t,ramp);grid on
axis([-10 10 -.5 1.5])
Alternative Representations: The ramp signal can also be represented using the MAX
function as:
%% or use the max property
ramp=max(0,t);
figure; plot(t, ramp);grid on
example
% Generate Ramp Signal using MAX function
ramps = max(0, t);
% Plot the Ramp Signal
figure;
plot(t, ramps, 'b', 'LineWidth', 2); grid on;
xlabel('Time (t)');
ylabel('Amplitude');
title('Continuous-Time Ramp Signal using MAX function');
axis([-5 5 -1 6]); % Adjust axis for better visualization
6
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
D. Sinusoidal signal
General expression for sinusoidal signal is
𝑥(𝑡) = 𝐴 cos(2𝜋𝑓𝑡 + 𝜃) = 𝐴 cos(𝑤𝑡 + 𝜃) 𝑓𝑜𝑟 𝑎𝑙𝑙 𝑡
• The amplitude (A): Determines the maximum height of the wave.
• Ordinary Frequency (𝑓): Defines how many complete oscillations occur in one
second.
• Angular Frequency (𝜔): Defines as 𝑤 = 2π f represents the rate of change of the
function's argument in radians per second.
• Phase (𝜃): Specifies the initial position of the wave at 𝑡 = 0 (measured in radians).
Determines whether the wave starts from a peak, zero crossing, or another point.
7
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
MATLAB script to visualize the sinusoidal function and demonstrate the effects of
amplitude, frequency, angular frequency, and phase shift.
% Define parameters
A = 2; % Amplitude
𝑓 = 1; % Frequency in Hz
omega = 2*pi* 𝑓; % Angular frequency (rad/s)
theta = pi/4; % Phase shift in radians
% Define time vector
t = 0:0.01:5; % Time from 0 to 5 seconds with 0.01 step
% Generate sinusoidal signal
x = A * cos(omega * t + theta);
% Plot the signal
figure;
plot(t, x, 'b', 'LineWidth', 2);
grid on;
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Sinusoidal Signal: A = ', num2str(A), ...
', 𝑓 = ', num2str(𝑓), ' Hz, \theta = ', num2str(theta), ' rad']);
legend('x(t) = A cos(\omega t + \theta)');
axis([0 5 -A-1 A+1]); % Adjust axis for better visualization
Or
%%Time specifications:
𝑓𝑠 = 1000; % samples per second
t = 0: 1/𝑓𝑠 :.1; % seconds
%%Sine wave:
𝑓𝑐 = 60; % hertz
A=2; %amplitude
theta=0; % originally phase=0
x = A*sin(2*pi*𝑓𝑐 *t+theta); %try sin or cos
Tasks:
1. Generate the signal [u(t)-u(t+1)] using Heaviside function.
2. Generate unit step signal with variable shift. Note: use input statement to ask user to
enter the shifting value.
3. Generate impulse signal with variable shift. Note: use input statement to ask user to
enter the shifting value.
4. Generate ramp signal that intersect with x-axis with variable shift. Note: use input
statement to ask user to enter the shifting value.
8
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
5. Use subplot to plot six sinusoidal signals with carrier frequency 4,6,8,10,12, and 20 Hz
respectively, amplitude A=3, and theta = 0.
9
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
Experiment No. 3
Properties of Signals
Aim:
• Investigate and analyze discrete-time signals to determine their periodicity and, if they
are periodic, to identify their fundamental periods.
• Perform mathematical operations on signals (addition, subtraction, multiplication, and
division) and observe their effects.
Theory:
In discrete-time signal analysis, determining the periodicity of a signal and identifying its
fundamental period are essential tasks. A discrete-time signal 𝑥 [n ] is defined as periodic if
there exists a positive integer 𝑁 such that:
𝑥 [n +N]= 𝑥[ n] ∀n.
The smallest positive value of N for the signal is referred to as the fundamental period of
the signal. If no such N exists, the signal is considered non-periodic.
2𝜋𝑀
Specifically, 𝑤𝑜 = , where M and 𝑁 are integers with no common factors other than
𝑁
1.
1
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
2𝜋𝑀
Normalized frequency 𝑤𝑜 =
𝑁
2𝜋𝑘 2𝜋𝑀
𝑤𝑜 𝑁𝑜 =2πk , 𝑁𝑜 = , substituting 𝑤𝑜 =
𝑤𝑜 𝑁
2𝜋𝑘 𝑁𝑘
𝑁𝑜 = 2𝜋𝑀 = ,
𝑀
𝑁
𝑁
Since 𝑁𝑜 must be the smallest positive integer, so set k =1. If 𝑁𝑜 = is an integer, it
𝑀
represents the fundamental period. If not, the signal is non- periodic.
2
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
• Assume N = 6 for each signal. Determine whether each signal periodic. If a signal is
periodic, plot the signal for two periods, starting at n = 0.
• Plot the signal for 0 ≤ n ≤ 7N and explain why it is periodic or not.
• Remember to use stem and to appropriately label your axes.
We take the Least Common Multiple (LCM) of the denominators 3 and 2, which is 6.
𝑥2 [𝑛] is periodic with fundamental period 6.
3
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
Tasks:
- Repeat x1 with M=12,20. If periodic find the fundamental period.
- Repeat x1 with N=6 for M=4,5. If periodic find the fundamental period
- Repeat
3𝑛 5𝑛
𝑥2[𝑛] = 2 cos ( ) + cos ( )
𝑁 𝑁
- Repeat x3 for N=4;
Operations on Signals
1. Addition & Subtraction
Signals can be added and subtracted on condition which is that they be of the same length
when defined in MATLAB in order to add or subtract the adjacent elements or values of the
signals.
In MATLAB, when you add or subtract signals (which are typically represented as vectors or
arrays), they must be the same length. MATLAB performs these operations element-wise,
meaning that the first element of one signal is added to the first element of the other, the
second element to the second, and so on. If the signals have different lengths, MATLAB will
return an error because it cannot match elements properly.
Example: For the following two signals
𝑋1 (𝑛) = (0.5)𝑛 − 10 ≤ 𝑛 ≤ 10
𝑋2 (𝑛) = (0.8)𝑛 − 10 ≤ 𝑛 ≤ 10
Using subplot to stem 𝑋1 , 𝑋2 , 𝑋1 + 𝑋2 , 𝑋1 − 𝑋2 .
Procedure:
1. Defined variable n from -10 to 10.
2. signal Definitions:
X1 = (0.5). ^n; calculates ( 0.5 )^n for each element in n.
X2 = (0.8). ^n;; calculates ( 0.8 )^n similarly.
Subplots:
The first subplot shows 𝑋1 (𝑛)
The second subplot shows 𝑋2 (𝑛)
The third subplot shows the element-wise sum 𝑋1 (𝑛) + 𝑋2 (𝑛)
The fourth subplot shows the element-wise difference 𝑋1 (𝑛) − 𝑋2 (𝑛)
4
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
You can determine the minimum and maximum values of any signal using the min and
max functions in MATLAB.
Example: For the following signal
𝑛
𝑋5 (𝑛) = 𝑐𝑜𝑠 (𝑝𝑖 ∗ ) − 20 ≤ 𝑛 ≤ 20
4
a) Find the maximum value and minimum values in X5 (n).
b) Use ‘find’ command to locate all indexes of the max and min values.
c) First stem X5 (n) then stem max and min according to their indexes.
Procedure:
1. Define the range of n from -20 to 20.
𝑛
2. Compute the signal 𝑋5 (𝑛) = 𝑐𝑜𝑠 (𝑝𝑖 ∗ )
4
3. Find the maximum and minimum values using max() and min().
4. Find their indices using the find() command.
5. Plot the signal using stem(), and:
• Highlight the max values in red.
• Highlight the min values in green.
6
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali
Task1:
Consider the two signals:
𝑋1 (𝑛) = 𝑒 0.2𝑛 − 10 ≤ 𝑛 ≤ 10
𝜋𝑛
𝑋2 (𝑛) = sin ( ) − 10 ≤ 𝑛 ≤ 10
4
Plot 𝑥1 (n) and 𝑥2 (n)
Compute and plot 𝑥1 (n) + 𝑥2 (n)
Compute and plot 𝑥1 (n) * 𝑥2 (n)
Use subplot to display all four plots in one figure.
Task2:
Given the signal 𝑋3 (𝑛) = 0.7𝑛 0 ≤ 𝑛 ≤ 10
Plot 𝑥3 (n)
Compute and plot the time-reversed signal 𝑥3 (-n)
Compute and plot 𝑥3 (n) + 𝑥3 (-n)
Use subplot to display all four plots in one figure.