You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数字信号处理课程求助:Matlab用嵌套循环实现DTFT(非符号数学)

Fixing Your DTFT Implementation with Nested For Loops in MATLAB

Hey there! Let's get your discrete-time Fourier transform (DTFT) code working properly using nested for loops (no symbolic math needed). I'll walk through the issues in your current code and provide a corrected version that generates the DTFT with $\omega$ as the independent variable.

First, Let's Clarify the DTFT Formula

The DTFT of a finite-length sequence $x[n]$ (for $n = 0$ to $N-1$) is defined as:

$X(e^{j\omega}) = \sum_{n=0}^{N-1} x[n] e^{-j\omega n}$

Your current code mixes up DTFT (continuous $\omega$ from $-\pi$ to $\pi$) with DFT (discrete frequency points $2\pi k/N$). Let's fix that.

Issues in Your Original Code

  • Uninitialized arrays: You never create the X array to store results, and Y isn't properly assigned back to X.
  • Incorrect frequency variable: You're using DFT-style discrete frequencies instead of the continuous $\omega$ values from your linspace call.
  • Loop range mismatch: bw = 1000 but linspace(-pi, pi, 1000) creates 1000 points, so your outer loop runs 1001 times (0 to 1000), which doesn't align.

Corrected Code

% Define your input sequence x (example: 8-point rectangular sequence)
N = 8;
x = ones(1, N); % Replace with your own sequence

% Set up frequency axis (omega)
lower = -pi;
upper = pi;
num_points = 1000;
omega = linspace(lower, upper, num_points);

% Initialize X as a complex array to store DTFT results
X = zeros(1, num_points) + 0j;

% Nested for loops to compute DTFT
for idx = 1:num_points
    current_omega = omega(idx);
    for n = 0:N-1
        % Accumulate the sum for the current omega
        X(idx) = X(idx) + x(n+1) * exp(-1j * current_omega * n);
    end
end

% Plot the magnitude of the DTFT (common visualization)
figure;
plot(omega, abs(X));
xlabel('$\omega$ (radians/sample)');
ylabel('$|X(e^{j\omega})|$');
title('DTFT of 8-Point Rectangular Sequence');
grid on;

Key Changes Explained

  • Input sequence definition: Added x (you'll want to replace this with your actual signal).
  • Complex array initialization: X is initialized as a complex array to handle the imaginary components of the DTFT.
  • Proper loop structure: The outer loop iterates over each continuous $\omega$ value, and the inner loop computes the sum from the DTFT formula.
  • Matlab indexing: Since Matlab uses 1-based indexing, we access x(n+1) for the $n$-th sample of the sequence.

What This Does

This code will generate a continuous DTFT spectrum across $\omega \in [-\pi, \pi]$, which matches the theoretical DTFT of your input sequence. For the example rectangular sequence, you'll see a sinc-shaped magnitude spectrum—this is the expected result!

内容的提问来源于stack exchange,提问作者Beshoy Hanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:44:55