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

MATLAB转Python:FFT与fftshift代码结果不匹配求助

Fixing MATLAB-to-Python FFT/FFTShift Mismatch

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 S is identical in both languages: If S is an array, double-check indices (MATLAB uses 1-indexing, Python uses 0-indexing—avoid off-by-one errors).
  • Compare intermediate outputs: Print the initial h array in both environments first. If h matches but FFT results don't, confirm you're not using scaled FFT functions (stick to np.fft.fft to match MATLAB's base fft).

内容的提问来源于stack exchange,提问作者Alireza Hassani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:01:27