我正在尝试将MATLAB
代码写入python
。原始MATLAB
代码来自以下视频:https://www.youtube.com/watch?v=T97ddyTMuro.简而言之,MATLAB
代码如下:
v = 10;
theta = linspace(15, 75, 100);
g = 9.81;
t = 2*v*sin(theta)/g;
r = v*cos(theta).*t;
plot(r,theta)
我试图在python
中重新创建此代码,随函附上我尝试过但失败的内容:
import numpy as np
import math as m
import matplotlib.pyplot as plt
theta = np.linspace(0,70,100)
v = 10 # velocity (m/s)
g = 9.81 # accel. due to grav.
t = []
r = []
a = []
multi =[]
for i in np.linspace(0,70,100):
t.append(2*v*(m.sin(np.deg2rad(i)))/g)
for j in np.linspace(0,70,100):
r.append(v*(m.cos(np.deg2rad(i))))
a.append(r[j]*t[j])
无法将两个lists
相乘,因为它们不是整数。
一种更简单的方法是直接使用numpy
代码:
import numpy as np
import matplotlib.pyplot as plt
theta = np.deg2rad(np.linspace(0,70,100))
v = 10 # velocity (m/s)
g = 9.81 # accel. due to grav.
t1 = 2*v*np.sin(theta)/g
r = v*np.cos(theta)*t1 # will compute elementwise multiplication
plt.plot(r, theta)
plt.show()