在while循环中重复while循环

时间:2017-10-02 21:42:20

标签: matlab

x = [];
i = 0;
p = 0;
count = 0;
hold on
while 1

if count == 100
    break;
end

while 1
n = rand(1); 
if i > 499
break;
end

if n > 0.5
p = p+1;
end
if n < 0.5
p = p-1;
end
if n==1
p = p;
end
i = i+1;
x(i) = p;
end

X = abs(x);
Y = 1:length(X);

ps = csapi(X,Y);

plot(X,Y,'o');
fnplt(ps)

count = count +1;
end
hold off
grid on
title('Random Walk Distances')
xlabel('Distance from the Origin')
ylabel('Each Iteration of the Experiment')

我想在我的初始while循环中重复这个过程,在一个图上有多条曲线,我还想找到我绘制的曲线的平均曲线,对于如何做到这一点的任何想法? / p>

1 个答案:

答案 0 :(得分:0)

此代码为您提供了一个图中的所有图。但是,如果你这样做,它看起来更像是一幅画,就像曲线的概述一样。我还清理了一下你的代码。如果您知道循环需要运行多少次以及没有其他触发器来打破循环,那么使用while循环是没用的。所以你可以把它们改成for循环。

close all;
p = 0;
hold on
for count = 0:99

    x = cell(1,1);

    for i = 1:499

        n = rand(1); 

        if n > 0.5
            p = p+1;
        end

        if n < 0.5
            p = p-1;
        end

        if n==1
            p = p;
        end

        x{i} = p;
    end

    x = cell2mat(x);
    X = abs(x);
    Y = 1:length(X);

    ps = csapi(X,Y);

    plot(X,Y,'o');
    fnplt(ps)    

end

hold off
grid on
title('Random Walk Distances')
xlabel('Distance from the Origin')
ylabel('Each Iteration of the Experiment')

enter image description here

相关问题