使用列表的算术运算



我正在尝试将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()

相关内容

  • 没有找到相关文章

最新更新