MATLAB转Python:FFT与fftshift代码结果不匹配求助
Let's break down the key differences between your MATLAB code and Python code that's causing inconsistent results, along with a corrected implementation:
1. Array Length Mismatch
Your MATLAB code creates a 1×Modes_number array, but your Python code initializes a 1×(Modes_number+1) array. This extra element makes the FFT output length different from MATLAB's—an immediate source of mismatch.
2. Unnecessary Loop & Data Type Alignment
MATLAB uses double-precision complex numbers by default, so in Python you should explicitly use np.complex128 to match this precision. Also, you don't need a loop to assign values to the row—vectorized assignment is cleaner and aligns with MATLAB's behavior.
3. FFT/FFTShift Axis Consistency
MATLAB's fft() operates on columns by default for 2D arrays, which matches NumPy's np.fft.fft() default (operating on the last axis). Both fftshift() functions also default to shifting all dimensions, so no extra axis parameters are needed here.
Corrected Python Code
import numpy as np # Match MATLAB's array dimensions (1 row, Modes_number columns) h = np.zeros((1, self.cfg.Modes_number), dtype=np.complex128) # Vectorized assignment (no loop required) h[0, :] = -1j * S # Compute FFT (aligns with MATLAB's fft(h) for 2D arrays) hfft = np.fft.fft(h) # Apply fftshift (matches MATLAB's fftshift behavior) hft0 = np.fft.fftshift(hfft)
Additional Checks to Ensure Full Match
- Verify
Sis identical in both languages: IfSis an array, double-check indices (MATLAB uses 1-indexing, Python uses 0-indexing—avoid off-by-one errors). - Compare intermediate outputs: Print the initial
harray in both environments first. Ifhmatches but FFT results don't, confirm you're not using scaled FFT functions (stick tonp.fft.fftto match MATLAB's basefft).
内容的提问来源于stack exchange,提问作者Alireza Hassani

