我想把matlab代码转换成python代码。
clear all ; clc
m = 20; c = [5,40,200]; k =20 ;
ta = 0 ; tb = 120 ; h = 0.1;
x = 1;
z = 0;
t = ta:h:tb;
n = (tb-ta)/h;
hold on ; grid on
fprintf('n i tt x tt t tt v n')
for p = 1:size(c(:))
f = @(x,t,z)z;
g = @(x,t,z)(-(c(p)*z)-(k*x))/m;
for i = 1:n+1
k1 = h*f(x(i),t(i),z(i));
l1 = h*g(x(i),t(i),z(i));
k2 = h*f(x(i)+(h/2),t(i)+(k1/2),z(i)+(l1/2));
l2 = h*g(x(i)+(h/2),t(i)+(k1/2),z(i)+(l1/2));
k3 = h*f(x(i)+(h/2),t(i)+(k2/2),z(i)+(l2/2));
l3 = h*g(x(i)+(h/2),t(i)+(k2/2),z(i)+(l2/2));
k4 = h*f(x(i)+h,t(i)+k3,z(i)+l3);
l4 = h*g(x(i)+h,t(i)+k3,z(i)+l3);
x(i+1) = x(i) +((1/6)*(k1+(2*k2)+(2*k3)+k4)*h);
z(i+1) = z(i) +((1/6)*(l1+(2*l2)+(2*l3)+l4)*h) ;
fprintf(' %d t %f t %f t %f n',i,x(i),t(i),z(i));
end
end
我制作的python代码如下:
import numpy as np
m = 20
c = np.array([[5,40,200]])
k =20
ta = 0 ; tb = 120 ; h = 0.1;
x = 1
z = 0
t = np.arange(ta,tb,h)
n = (tb-ta)/h
print('n i tt x tt t tt v n')
for p in np.shape(c.T):
f = lambda x,t,z : z
g = lambda x,t,z : (-(c(p)*z)-(k*x))/m
for i in np.arange(1,n+1):
k1 = h*f(i,i,i)
l1 = h*g(i,i,i)
k2 = h*f(i+(h/2),i+(k1/2),i+(l1/2))
l2 = h*g(i+(h/2),i+(k1/2),i+(l1/2))
k3 = h*f(i+(h/2),i+(k2/2),i+(l2/2))
l3 = h*g(i+(h/2),i+(k2/2),i+(l2/2))
k4 = h*f(i+h,i+k3,i+l3)
l4 = h*g(i+h,i+k3,i+l3)
x = (i+1) = i +((1/6)*(k1+(2*k2)+(2*k3)+k4)*h)
z = i+1 = i +((1/6)*(l1+(2*l2)+(2*l3)+l4)*h)
print('{:.3f}t{:.3f}t{:.3f}t{:.3f}',i,x(i),t(i),z(i))
我对此感到困惑x(i+1) = ....; z(i+1) = ....;
在matlab代码中,因为x(…(和z(…(在我的python代码中无法识别。如何在python代码中表示这一行?
您需要使用方括号,而不是括号x[i]。此外,python中的索引从0开始(不像matlab从1开始(。所以它应该是x[i]=x[i-1]+。。。