MATLAB Answers

Matlab Code for DTFT to get frequency response

16 views (last 30 days)
Siddhant Sharma
Siddhant Sharma on 26 Mar 2021
Answered: Paul on 27 Mar 2021
I am trying to run this code to get frequency response of h[n]:
clc;
clear;
n = 0:5;
h = [1, 0, -2, 3, 0, -2];
w = -pi:0.001:pi;
H = h.*exp(-1i*w*n);
H_mag = abs(H);
H_pha = angle(H);
subplot(2,1,1);
plot(w, H_mag, 'linewidth', 2);
grid
xlabel('\omega ');
ylabel('|H(e^{j\omega})|');
title('Magnitude Plot');
subplot(2,1,2);
plot(w, H_pha, 'linewidth', 2);
grid
xlabel('\omega ');
ylabel('\angle H(e^{j\omega}) (degrees)');
title('Angle Plot');
But I am receiving the following error:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the
number of rows in the second matrix. To perform elementwise multiplication, use '.*'.
Error in B_e (line 9)
H = h.*exp(-1i*w*n);
I am not very proficient in Matlab so not able to identify the issue. Since I am using only one matrix, not able to see how can I do the required multiplication.

Answers (1)

Paul
Paul on 27 Mar 2021
n, h, and w are all defined as row vectors and the * operator is trying to do matrix multiplication. But what you really want is to use the .* (note the dot in front of the *) to do element-by-element multiplication. Inside the exp function you want to generate a 2d array. That array should looke like this:
[w(1)*0 w(1)*1 w(1)*2 ..... w(1)*5
.
.
.
w(N)*0 w(N)*1 w(N)*2 ..... w(N)*5]
where N is the number of elements in w. Such a matrix can be formed by:
temp = w(:) .* n(:).'
using a feature called automatic implicit expansion. w(:) stretches w as colument and n(:).' ensures it's a row vector. Try with some simple variables:
>> w = 0:2; n = 0:3;
>> w(:) .* n(:).'
ans =
0 0 0 0
0 1 2 3
0 2 4 6
Now you need the exponential of that matrix multiplied by -1j
>> exp(-1j * w(:) .* n(:).')
ans =
1.0000 + 0.0000i 1.0000 + 0.0000i 1.0000 + 0.0000i 1.0000 + 0.0000i
1.0000 + 0.0000i 0.5403 - 0.8415i -0.4161 - 0.9093i -0.9900 - 0.1411i
1.0000 + 0.0000i -0.4161 - 0.9093i -0.6536 + 0.7568i 0.9602 + 0.2794i
Now we need to mulitply each row of this marix by the sequence h[n]
>> h(:).' .* exp(-1j * w(:) .* n(:).')
ans =
0.0000 + 0.0000i 1.0000 + 0.0000i 2.0000 + 0.0000i 3.0000 + 0.0000i
0.0000 + 0.0000i 0.5403 - 0.8415i -0.8323 - 1.8186i -2.9700 - 0.4234i
0.0000 + 0.0000i -0.4161 - 0.9093i -1.3073 + 1.5136i 2.8805 + 0.8382i
Each row of this matrix is h*exp(-1j*w*n) evaluated at a single value of w and all values of h. So the last step is to sum across the columns. Note the result is a column vector
>> H = sum(h(:).' .* exp(-1j * w(:) .* n(:).'),2)
H =
6.0000 + 0.0000i
-3.2620 - 3.0834i
1.1571 + 1.4426i
Let's try with your data:
>> w = -pi:.001:pi;
>> h = [1 0 -2 3 0 -2];
>> n = 0:5;
>> H = sum(h(:).' .* exp(-1j * w(:) .* n(:).'),2);
>> plot(w,abs(H))

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!