我对编程非常陌生,因此请耐心等待我的回复。我正在尝试将matlab的示例代码转换为python,但是我在for循环中遇到了数组问题,并不断收到索引错误。将Matlab转换为Python,数组和循环出错
这里是给定的MATLAB代码:
clear all
close all
clc
m=100; %kg
k=1000; %N/m
c=25;
v0=0;
x0=0;
dt=0.0005;
F=1000; % N the mag of input force
f0=F/m;
w=2.5; %rad/sec input frequency
t=0:dt:10;
wn=(k/m)^0.5;% rad/sec natural frequency
ze=c/(2*(k*m)^0.5);
A=[0 1; -wn^2 -2*ze*wn];
X0=[x0;v0]; %intial conditions
for i=1:length(t)
X(:,i)=X0;
Finput=[0;f0*cos(w*t(i))];
X0=X0+A*X0*dt+dt*Finput;
end
figure,plot(t,X(1,:));
title('Displacement vs tiem')
xlabel('time (second)')
ylabel('Displacement')
grid on
figure,plot(t,X(2,:),'r');
xlabel('time (second)')
ylabel('Velocity')
我的代码
import numpy as np
import matplotlib.pyplot as plt
#constants
k=1000
m=100
v0=0.0
x0=0.0
f=1000
c=25
f0 = f/m
wn = np.sqrt(k/m)
w = wn*2
ze =c/(2*(k*m)**0.5)
A = np.array([[0.0,1.0],[-wn**2,-2*ze*wn]])
X0= np.array([x0,v0])
dt = 0.01
t = np.arange(0, 2.5, dt) #get values between -10 and 10 with 0.01 step and set to y
for i in range (len(t)):
print(X0)
X0[:,i]=X0 #error
print(X0)
Finput = np.array([0.0,(f0*np.cos(w*dt*i))])
X0 = X0 + A*dt*X0+dt*Finput
plt.plot(t, X0[0,:])
plt.plot(t, X0[1,:])
plt.show()
我不断收到 “IndexError:数组太多指数” 为X0 [:,i] = X0一部分在我的for循环中,我正在努力弄清楚为什么。
很多预先感谢您的帮助!
实际上,'X0'到'X0' * row *。专业,专业。 –