【问题标题】:Conducting a while-loop in Matlab with arrays在 Matlab 中使用数组进行 while 循环
【发布时间】:2015-11-29 16:23:37
【问题描述】:

我有以下练习:

在这个练习中,我们将使用一个非常简单的地球模型(陆地 仅)在其上生长草。部分的净变化率 草覆盖的地球面积 (A) 由下式给出:dA/dt = A((1-A).G-D),其中 D 是死亡率(常数为每 10 万年 0.1 次)。草的生长速度为每 10 万年 (G) 0.4。 离散这个方程。使用离散方程计算 A 作为时间的函数。程序中的每个时间步长对应于 1000 万年。将模型运行 200 个时间单位(即 20 亿年)。使用 0.001 的 A 起始值。在屏幕上写入增长稳定的时间(这里定义为一个时间步长的变化小于所考虑时间的 A 与 A 的初始值相比差异的 1%。 p>

现在我得到了这个脚本:

clear all

%Define variables

D=0.1;
G=0.4;
A=0.001;
dt=10E6; %timestep
timevector=[];
grassvector=[];
startloop=1;
endloop=200;

%Define the loop

for t=startloop:endloop
    A=A.*((((1-A).*G)-D)) + A;   
    grassvector(t)=A;
    timevector(t)=t*dt;
end

plot(timevector, grassvector)

到目前为止,它似乎工作正常。但我无法弄清楚问题的第二部分。我认为它可以用一个while循环来完成,但Matlab一直给我错误。

clear all

D=0.1;
G=0.4;
A=0.001;
dt=10E6;
t=0;
timevector=[];
grassvector=[];

while A(t+1)-A(t) > 0.01(A(t)-A)
    t=(t+1)*dt;
    A=A.*((((1-A).*G)-D)) + A;  
    grassvector(t)=A;
    timevector(t)=t*dt;
end

有人可以帮忙吗? 谢谢!

【问题讨论】:

  • 您的代码中实际上有很多拼写错误。在 MATLAB 中不能有 A(0)0.01(A(t)-A) 中也没有 *。以此类推。
  • 如果以下答案满足您的问题,请标记为接受。

标签: arrays matlab loops while-loop


【解决方案1】:

我不知道你在做什么,但你可能想要这样的东西:

D=0.1;
G=0.4;
A=0.001;
dt=10E-6;             % should be a small value
t=0;                  % initial zero time, cannot be used as index in matlab
steps = 100;          % say you want to calculate up to 100 iterations
timevector=zeros(1,steps);
grassvector=zeros(1,steps);    
timevector(1,1) = t;  % initialize the vectors with initial values
grassvector(1,1) = A;
ii = 1;

while (abs(grassvector(1,ii+1) - grassvector(1,ii)) > 0.01 * (grassvector(1,ii))) && (ii < steps-1)
    t = (t+1)*dt;
    grassvector(1,ii+1) = grassvector(1,ii) * ((1-grassvector(1,ii))*G - D) + grassvector(1,ii);
    timevector(1,ii+1) = t*dt;
    ii = ii + 1;
end

在 while 循环的条件下,我猜你想检查 delta(A) 是否超过一个小值。您还必须检查是否重复指定的步骤数。否则,您应该以另一种方式处理内存管理。 在循环内部,您还可以摆脱 At 的常量值并直接使用向量。

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 2016-09-18
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2015-02-20
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多