我正在尝试为以下程序预分配内存以提高计算速度。
global k1 k2 k3 k4 k5
k1=50;
k2=2.0e+03;
k3=5e+01;
k4=.0001;
k5=200;
dt=0.0001;
x(1)=0.9999;
y(1)=0.38462;
z(1)=0.1995;
t(1)=0.0;
for i=1:100000
t(i+1)=t(i)+dt;
x(i+1)=x(i)+dt*(-k5*(k1+k3)*x(i)+ k3*x(i)*z(i) + k4*z(i) + k2*y(i) );
y(i+1)=y(i)+dt*(k1*x(i) - k2*y(i));
z(i+1)=z(i)+dt*(-k3*x(i)*z(i) - k4*z(i) + k3*k5);
end
%plot(t,x,'b');
%plot(t,y,'g');
plot(t,z,'r');
%plot3(x,y,z);
%legend('x','y','z');
%hold on;
grid on;
%axis([0 10 0 10 0 10]);
%end
请帮助。提前谢谢。
答案 0 :(得分:2)
由于您知道每个阵列中有100000个+ 1个条目,因此很容易预分配
n = 100001;
x = zeros(n,1); %//pre-allocation
y = zeros(n,1);
z = zeros(n,1);
t = zeros(n,1);
x(1)=0.9999; %//setting init-values
y(1)=0.38462;
z(1)=0.1995;
t(1)=0.0;
for ii=1:( n - 1 )
t(ii+1)=t(ii)+dt;
x(ii+1)=x(ii)+dt*(-k5*(k1+k3)*x(ii)+ k3*x(ii)*z(i) + k4*z(ii) + k2*y(ii) );
y(ii+1)=y(ii)+dt*(k1*x(ii) - k2*y(ii));
z(ii+1)=z(ii)+dt*(-k3*x(ii)*z(ii) - k4*z(ii) + k3*k5);
end