В настоящее время я пытаюсь улучшить свои навыки работы с Python, используя его для воссоздания некоторых старых проектов Matlab, которые я делал в бакалавриате. Однажды я использовал Matlab для моделирования протона, притягивающего электрон, используя многомерные массивы для хранения положений и скоростей для каждого временного шага. Теперь я пытаюсь сделать то же самое в Python, но способ работы массивов сильно отличается от того, как они используются в Matlab. Я сталкиваюсь с множеством ошибок и выясняю ситуацию по ходу дела, но думаю, что застрял в размышлениях о массивах в «путе Matlab», и некоторые моменты о том, как это сделать в Python, были бы очень признательны.
Код: Выделить всё
#This code is for plotting the trajectory of an electron travelling through space
#The particle is in the vacinity of a central force (A proton at the origin)
import numpy as np
import matplotlib.pyplot as plt
re = np.array([[1e-11],[1e-11]]) #let re denote the trajectory of the electron with x = r[0] and y = r[1]
m = 9.11e-31 #mass of electron
k = 8.99e9 #Coulomb's constant [N m^2/C^2]
q = 1.6e-19 #charge of electron and proton [C]
rp = [0,0] #rp is the position of the proton
dt = 0.001 #time differential [s]
v = np.array([[-3e12],[0]]) #the electron has initial velocity of v = (-3, 0) [m/s]
phi = np.arctan2(re[1][0], re[0][0]) #starting angle
for i in range(1,10):
# nrex = (re[0][i-1])+v[0][i-1]*dt #nuew position in x
# nrey = (re[1][i-1])+v[1][i-1]*dt #new position in y
re[0] = np.append(re[0], ((re[0][i-1])+v[1][i-1]*dt), axis=1) #, axis=1) #for each timestep move the velocity in x
re[1] = np.append(re[1], ((re[1][i-1])+v[1][i-1]*dt), axis=1) #for each timestep mobe the velocity in y
phi = np.arctan2(re[1][i],re[0][i]) #update the angle
rho = np.sqrt(re[0][i]**2 + re[1][i]**2) #update separation from proton
v[0] = np.append(n[0], (v[0][i-1]+((k*(q**2)/(rho**2))/m)*np.cos(phi)*dt), axis=1) #update velocity in x
v[1] = np.append(v[1], (v[1][i-1]+((k*(q**2)/(rho**2))/m)*np.sin(phi)*dt), axis=1) #update velocity in y
plt.scatter(re[0][:], re[1][:], s=2, c='b') #Plot electron's trajectory
plt.scatter(rp[0],rp[1], s=3, c='r') #Show proton's position
plt.show() #Show
Код: Выделить всё
Traceback (most recent call last):
File "c:\Users\hecto\OneDrive\Documentos\ITESM\8vo semestre\Repaso Python\ParticleInElectricField.py", line 20, in
re[0] = np.append(re[0], ((re[0][i-1])+v[1][i-1]*dt), axis=1) #, axis=1) #for each timestep move the velocity in x
File "", line 200, in append
File "C:\Users\hecto\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\function_base.py", line 5499, in append
return concatenate((arr, values), axis=axis)
File "", line 200, in concatenate
numpy.AxisError: axis 1 is out of bounds for array of dimension 1
PS C:\Users\hecto\OneDrive\Documentos\ITESM\8vo semestre\Repaso Python>
When I tried the same code withoue the "axis=1" i returned an erro about the dimensions of the array. This is probably because without it, np.append flattens the vector. When I try "axis=0", the error becomes:
Код: Выделить всё
Traceback (most recent call last):
File "c:\Users\hecto\OneDrive\Documentos\ITESM\8vo semestre\Repaso Python\ParticleInElectricField.py", line 20, in
re[0] = np.append(re[0], ((re[0][i-1])+v[1][i-1]*dt), axis=0) #, axis=1) #for each timestep move the velocity in x
File "", line 200, in append
File "C:\Users\hecto\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\function_base.py", line 5499, in append
return concatenate((arr, values), axis=axis)
File "", line 200, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index
1 has 0 dimension(s)
Источник: https://stackoverflow.com/questions/781 ... -in-matlab