matlab转python语言
时间: 2023-08-09 15:05:34 浏览: 132
这里给出一些常用的 MATLAB 语句及其 Python 对应语句:
1. 变量赋值
MATLAB:
```
a = 1;
b = [1, 2, 3];
c = 'hello';
```
Python:
```
a = 1
b = [1, 2, 3]
c = 'hello'
```
2. 数组索引
MATLAB:
```
a = [1, 2, 3];
b = a(2);
```
Python:
```
a = [1, 2, 3]
b = a[1]
```
3. 控制语句
MATLAB:
```
if a > 0
disp('positive')
elseif a < 0
disp('negative')
else
disp('zero')
end
```
Python:
```
if a > 0:
print('positive')
elif a < 0:
print('negative')
else:
print('zero')
```
4. 循环语句
MATLAB:
```
for i = 1:10
disp(i)
end
```
Python:
```
for i in range(1, 11):
print(i)
```
5. 函数定义
MATLAB:
```
function y = square(x)
y = x^2;
end
```
Python:
```
def square(x):
return x**2
```
6. 绘图
MATLAB:
```
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y)
```
Python:
```
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
```
这些是 MATLAB 到 Python 的一些常用语句的对应关系,但并不是全部,因为两种语言的语法和用法还是存在差异的。
阅读全文