matlab-python程序互转

软件: MATLAB
全方位数据报表
许可分析

许可分析

免费体验
识别闲置、及时回收
许可优化

许可优化

免费体验
多维度智能分析
许可分析

许可分析

免费体验
减少成本、盘活许可
许可优化

许可优化

免费体验

处理对比

欢迎浏览: matlab-python程序互转


Key Differences:

1. Matrix/Array Handling: Both MATLAB and Python (via NumPy) handle 1D arrays (vectors) similarly, yet the syntax for operations and indexing differs slightly.

Indexing: In MATLAB, array indexing starts at 1. In Python, indexing starts at 0.

Array Expansion (`hstack` vs Array Concatenation): MATLAB's `hstack` for horizontal concatenation corresponds to Python's array concatenation but differs in syntax and implementation.

Mathematical Expressions:

MATLAB uses direct mathematical notation suitable for documented equations, while the Python code uses NumPy for vector operations.

Looping:

The Python code explicitly slices the input array, adjusting for the delay by removing the first two elements before upsampling.

It uses NumPy for array operations and matplotlib for plotting.

MATLAB Original


```matlab


T = 1;


Fs = 2/T;


Ts = 1/Fs;


c_opt = [2.2 4.9 3 4.9 2.2];


t = 5T:T/2:5T;


x = 1./(1+((2/T)t).^2); % sampled pulse

equalized_x = filter(c_opt, 1, [x 0 0]); % since there will be a delay of two samples at the output

equalized_x = equalized_x(3:end);


figure(1)


stem(equalized_x)


figure(2)

stem(equalized_x(1:2:end)) % for downsampled equalizer output

```


Python Rewritten


```python


T = 1


Fs = 2/T


Ts = 1/Fs


c_opt = np.array([2.2,4.9,3,4.9,2.2])


t = np.linspace(5T, 5T, num=21)


x = 1/(1 + (2/T t)2)

x = np.hstack((x, np.zeros(2)))   Adjustment for delay in output

equalized_x = scipy.signal.lfilter(c_opt, [1], x)

equalized_x = equalized_x[2:]   Adjusted slicing to remove delayinducing elements

plt.figure(1)


plt.stem(equalized_x)


plt.figure(2)

plt.stem(equalized_x[::2])   For downsampled equalizer output

plt.show()


```


Key Points of the Revised Python Code:

The `.hstack()` equivalent is replaced using `np.hstack` for array concatenation, adjusting thezeros array for the delay effect correctly.

Explicit slicing to address the `delay` is altered to utilize Pythonic halfstep indexing for downsampling.

`scipy.signal.lfilter` is used directly without unnecessary array stacking, simplifying the process against the initial modification.

Conclusion:

This contrast showcases the adaptive nature of programming practices across languages, highlighting both similarities in handling mathematical operations and differences in syntax and array manipulation techniques.

index-foot-banner-pc index-foot-banner-phone

点击一下 免费体验万千客户信任的许可优化平台

与100+大型企业一起,将本增效

与100+大型企业一起,将本增效

申请免费体验 申请免费体验