matlab转python
时间: 2023-10-14 18:06:32 浏览: 79
这里提供一些常见的 MATLAB 语法和函数在 Python 中的等价物:
1. 读取和保存数据
MATLAB:
```
load('data.mat')
save('result.mat', 'var1', 'var2')
```
Python:
```
import scipy.io
data = scipy.io.loadmat('data.mat')
scipy.io.savemat('result.mat', {'var1': var1, 'var2': var2})
```
2. 数组和矩阵
MATLAB:
```
A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
B = [1, 2, 3]
C = ones(3, 3)
D = zeros(3, 3)
```
Python:
```
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([1, 2, 3])
C = np.ones((3, 3))
D = np.zeros((3, 3))
```
3. 控制流
MATLAB:
```
for i = 1:10
disp(i)
end
if a > b
disp('a is greater than b')
else
disp('b is greater than a')
end
```
Python:
```
for i in range(1, 11):
print(i)
if a > b:
print('a is greater than b')
else:
print('b is greater than a')
```
4. 绘图
MATLAB:
```
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y)
```
Python:
```
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
```
5. 高级数学函数
MATLAB:
```
y = exp(x)
y = log(x)
y = sin(x)
y = cos(x)
y = tan(x)
y = sqrt(x)
y = abs(x)
```
Python:
```
import numpy as np
y = np.exp(x)
y = np.log(x)
y = np.sin(x)
y = np.cos(x)
y = np.tan(x)
y = np.sqrt(x)
y = np.abs(x)
```
这里只是简单介绍了一些常见的 MATLAB 语法和函数在 Python 中的等价物,并不是全部的内容。对于更复杂的 MATLAB 代码,可能需要更深入的理解和转化。
阅读全文
相关推荐













