0% found this document useful (0 votes)
18 views26 pages

Ilovepdf Merged

The document provides an introduction to MATLAB programming, detailing its key features, including the Command, Figure, and Editor windows. It covers arithmetic operations, complex numbers, array indexing, memory allocation, and various special functions, along with plotting techniques and control structures like loops and conditional statements. The content is structured to guide students through practical MATLAB applications in engineering and science.

Uploaded by

dhwalfqarhsyn32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views26 pages

Ilovepdf Merged

The document provides an introduction to MATLAB programming, detailing its key features, including the Command, Figure, and Editor windows. It covers arithmetic operations, complex numbers, array indexing, memory allocation, and various special functions, along with plotting techniques and control structures like loops and conditional statements. The content is structured to guide students through practical MATLAB applications in engineering and science.

Uploaded by

dhwalfqarhsyn32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Signals and Systems LAB (SGSY257) 2nd year,2nd semester

Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra


Dr. Mohammed H. Ali

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

% Define data points


a =0:5; % X-coordinates
b =1:6; % Y-coordinates
Plot (a,b,'-x')

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:

im = 1i; % Define 'im' as the imaginary unit


z1 = 3 + 4*im; % Define a complex number
z2 = 2 - 5*im; % Another complex number

% 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

Method 2: Using linspace


y = linspace(1, 6, 6);

Method 3: Using [] (Explicit Definition)


y = [1 2 3 4 5 6];
This manually defines the vector.
Accessing Elements in the Array
• First element: y(1); Last element: y(end); Third element: y(3)

y(2) = 10; % Changes the second element to 10

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

C = [A B]; % Concatenate horizontally


D = [A; B]; % Concatenate vertically

To access a subset of the array, try the following:


y(3:6)
length(y) % gives the size of the array or vector
y(2:2:length(y))

Inserting Elements into a Vector


Insert an Element (3) at a Specific Position

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

y = rand(1, 100); % 1×100 vector with random values between 0 and 1

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,

F. Special Characters and Functions


Some common special characters used in MATLAB are given below:

special function is given below:

find - Finds indices of nonzero elements.


The function ‘find’ returns the indices of the vector X that are non-zero or matrix that meet a
specified condition.
returns a vector containing the linear indices of each nonzero element in array X.
For example, I = find(X> 4), finds all the indices of X when X is greater than 4.
X = [1 5 3 7 4 9];
I = find (X > 4)
I=
2 4 6
Example: Find the nonzero elements in a 3-by-3 matrix.
x = [1 0 2; 0 1 1; 0 0 4]
5
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

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

Combining Text and Numbers Using disp


disp(['Temperature = ' num2str(temp) ' Degrees F'])
For more control over formatting, use fprintf.
fprintf('Temperature = %.1f Degrees F\n', temp);

7
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

J. Control & Loop statements


1. if statement

In MATLAB, the if-elseif-else structure is used to execute statements based on


conditions.
Execute statements if condition is true.
if condition1
statement1;% Executes statement1 if condition1 is
true.
elseif condition2
statement2; % Checks condition2 if condition1 is
false.
else
statement3; %Executes statement3 if none of the
conditions are met.
end
Example
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
else
disp('a is odd')
end

2. switch & case statement


switch (expression)
case 0
statement 1; case 1
statement 2; case 2
statement 3;
otherwise
error( ’error statement'); % Executes if no case matches (optional but recommended).
end % Ends the switch block.
Example
n = input('Enter a number: ');
switch n
case -1
disp('negative one')
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp('other value')
end

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.

3. Loop Control – for


The for loop is used to repeat a set of statements for a fixed number of times. It is
commonly used for iterating over arrays, performing computations, and
automating repetitive tasks.
for i=1: n
statement(s);
end
Example use if and for ? At the end print the values of c & check
c = zeros(1,10); % Preallocate for efficiency
for a=1:10;
if a<3
c(a)=a^2;
elseif a<7
c(a)=a+5;
else
c(a)=a;
end
end
output: c = [1, 4, 8, 9, 10, 11, 7, 8, 9, 10]

4. Loop Control – while


The while loop in MATLAB is used when you do not know in advance how many
times the loop will run. It continues to execute as long as the condition is true.
while(condition =True)
statements;

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

Aim: Generation of continuous-time and discrete-time signals, including:


A. Step signal
B. Impulse signal
C. Ramp signal
D. Sinusoidal signal.
These are the basic signals. Plot all the 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:

%%Unit step generation


t = -10:0.01:10; % step is small enough to represent continuous-time signal
f=heaviside(t); % the unit step function.
figure; plot (t,f,'LineWidth', 2); grid on
axis([-10 10 -0.5 1.5])

%% simplified unit step generation(Using Logical Indexing)


t=-5:0.01:5; % step is small enough to represent continuous-time signal
unitstep = t >= 0;
figure; plot(t, unitstep, 'r', 'LineWidth', 2)
axis([-5 5 -0.5 1.5])
xlabel('Time (t)');
ylabel('u(t)');
title('Unit Step Function');
grid on
The heaviside function is defined easily such that it can shifted or reversed 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

same operations using simplifies method


%% shift left by 3
unitstep3 = t>=-3;
figure;
plot(t,unitstep3)
axis([-10 10 -0.5 1.5]);grid on;grid minor
%% shift right by 4
unitstep4 = t>=4;
figure;
plot(t,unitstep4)
%% folding
unitstep_fold = t<0;
figure;
plot(t,unitstep_fold)

2. Discrete Time Unit Step


The discrete-time unit step function, denoted as u[n] is a fundamental signal in digital
signal processing and discrete-time systems. It is defined mathematically as:
1 𝑛≥0
𝑢[𝑛] = {
0 𝑛<0
It is a causal signal because it is defined for 𝑛 ≥ 0 and remains zero for negative
indices. It is commonly used to represent system responses, digital filtering, and time-
domain signal processing.
MATLAB Code for Discrete-Time Unit Step Function
2
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

n = -10:10; % Define discrete-time index


unitstep = (n >= 0); % Unit step function definition
figure; stem(n, u, 'filled'); % Plot discrete-time signal
n=-10:10;
f=heaviside(n); % note that it is not defined at n=0 (mistake)
figure; stem(n,f)
xlabel('n');
ylabel('u[n]');
title('Discrete-Time Unit Step Function');
axis([-10 10 -0.5 1.5]);grid on; grid minor
OR

B. Unit Impulse signal


1. Continuous Time Unit Impulse
The unit impulse function is not a function in the strict sense while it is very useful in
the mathematical analysis of signals and especially signal which has discontinuities or
sudden changes. Also known as the Dirac Delta Function, it is defined as:
𝑢𝑛𝑑𝑒𝑓𝑖𝑛𝑒𝑑(∞) 𝑡 = 0
𝛿(𝑡) = {
0 𝑡≠0

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])

MATLAB Example: Impulse Function, Shifting, and Reversing


% Discrete version
n = -5:5;
delta_n = (n == 0); % Unit impulse function
% Shifted version
delta_shifted = (n == 2); % Shifted impulse δ[n - 2]

% Plot discrete impulse


subplot(3,1,1);
stem(n, delta_n, 'filled', 'LineWidth', 2);
xlabel('n'); ylabel('\delta[n]');
title('Discrete-Time Unit Impulse Function');
grid on;
% Plot shifted impulse
subplot(3,1,2);
stem(n, delta_shifted, 'filled', 'LineWidth', 2);
xlabel('n'); ylabel('\delta[n-2]');
title('Shifted Impulse Function (\delta[n-2])');
grid on;
% Plot reversed impulse
??????
another method to generate impulse in MATLAB.
%%%% continuous time
t=-10:0.01:10;
impulse = (t==0);
figure; plot(t, impulse);grid on
axis([-10 10 -0.5 1.5])

2. Discrete Time Unit Impulse


The issue arises because MATLAB does not inherently distinguish between the
continuous-time and discrete-time definitions of the delta function. Instead,

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])

another method to generate impulse in MATLAB.


%% discrete time
n=-10:10;
impulse = n==0;
figure; stem(n,impulse); 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

MATLAB Code for a Shifted Ramp Signal


% Shifting ramp to the right by 3
t = -10:0.01:10;
unitstep = t >= 3; % Generate unit step (u(t-3))
subplot(3,1,1);
plot(t, unitstep);
grid on;
axis([-10 10 -0.5 1]);
title('Unit Step (u(t - 3))');
% Generate ramp signal by multiplying t with unit step
ramp = t .* unitstep;
subplot(3,1,2);
plot(t, ramp);
grid on;

6
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Generating Fundamental Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

axis([-10 10 -0.5 5]);


title('Ramp Signal (r(t - 3))');

% OR use the max function to shift ramp to the right by 3


ramp_max = max(3, t); % Shift ramp by 3 units to the right
subplot(3,1,3);
plot(t, ramp_max);
grid on;
axis([-10 10 -0.5 5]);
title('Ramp Signal using max function (r(t - 3))');

2. Discrete Time Ramp


In discrete-time, the ramp signal is typically defined as:
𝑛, 𝑛≥0
𝑟[𝑛] = {
0, 𝑛<0
This means that the ramp signal increases linearly with 𝑛 when 𝑛 ≥ 0 and is 0 when
𝑛 < 0.
MATLAB Code for Discrete-Time Ramp:
%% simplified unit step generation
n=-10:10;
unitstep= (n>=0);
ramp = n.*unitstep;
figure;stem(n, ramp, 'b', 'LineWidth', 2);grid on
%% or use the max property
ramp=max(0,n);
figure; stem(n, ramp, 'r', 'LineWidth', 2);grid on

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.

For a sinusoidal signal,


𝑥 [n]= sin(𝑤𝑜 𝑛 + 𝜑) = sin(𝑤𝑜 (𝑛 + 𝑁) + 𝜑), is periodic if and only if the normalized
frequency 𝑤𝑜 is a rational multiple of π.
Using the identity sin(A+2π) =sin(A), this condition simplifies to:

𝑤𝑜 𝑁 =2πk, for some integer k


2πk
Which means 𝑤𝑜 =
𝑁

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

Example: Analyze the discrete-time signal


2𝜋𝑀𝑛
𝑥1 [𝑛] = sin ( )
𝑁
with N =12 and M taking values 4, 5, 7, and 10, plot each signal over the interval
0 ≤ n ≤ 2N −1. and determine their fundamental periods.

A discrete-time sinusoid is periodic if there exists a positive integer, 𝑁𝑜 such that:


𝑥1 [𝑛] = 𝑥1 [𝑛 + 𝑁𝑜 ]

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.

Calculations for Each M:


12
M = 4, 𝑁𝑜 = = 3 , (periodic with fundamental period 3) and so on. The outputs should
4
be as shown in the figure below.

2
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

All signals are periodic since every M yields a limited 𝑁𝑜 .

Now consider the following signals:


2𝑛 3𝑛
𝑥2 [𝑛] = 2 cos ( ) + cos ( )
𝑁 𝑁
2𝜋𝑛 5𝜋𝑛
𝑥3 [𝑛] = cos ( ) + 3 sin ( )
𝑁 2𝑁

• 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.

By comparing, we identify the frequencies of 𝑥2 [𝑛]:


2𝑛 2 2 1
First term 2 cos ( ) , 𝑤1 = = =
𝑁 𝑁 6 3
3𝑛 3 3 1
Second term 2 cos ( ) , 𝑤2 = = =
𝑁 𝑁 6 2
A discrete-time signal is periodic if there exists a smallest positive integer M
1 1
𝑀 = 𝑘1 ,and 𝑀 = 𝑘2
3 2

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

2. Multiplication & Division


In MATLAB, you can only multiply or divide two signals if they have the same length. Be
sure to avoid dividing by zero when performing element-wise operations. Also, remember to
use the dot operator (e.g., `.*` or `./`) for element-wise multiplication or division, especially
since our signals will generally be stored as horizontal vectors.
Example: For the following two signals
𝑋3 (𝑛) = (0.6)𝑛 − 10 ≤ 𝑛 ≤ 10
𝑋4 (𝑛) = (0.2)𝑛 − 10 ≤ 𝑛 ≤ 10
Using subplot to stem 𝑋3 , 𝑋4 , 𝑋3 ∗ 𝑋4 , 𝑋3 /𝑋4 .
Procedure:
1. Defined variable n from -10 to 10.
2. signal Definitions:
X3= (0.6). ^n; calculates ( 0.6 )^n for each element in n.
X4 = (0.2). ^n;; calculates ( 0.2 )^n similarly.
Subplots:
The first subplot shows 𝑋3 (𝑛)
The second subplot shows 𝑋4 (𝑛)
The third subplot shows the element-wise sum 𝑋3 (𝑛) ∗ 𝑋4 (𝑛)
The fourth subplot shows the element-wise difference 𝑋3 (𝑛)/𝑋4 (𝑛)
5
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Properties of Signals Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

3. Maximum & Minimum

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.

You might also like