How to loop an already looping code, in order to find output convergent value.

1 回表示 (過去 30 日間)
%I have code which includes a for and while loop which I have to loop one
%million times, to find a convergent output (probability).
sq=0;
i=1;
while sq<=250
sq(i)=i^2
i=i+1;
end
prime=primes(250)
pos=randi(255,1,1)
position=pos;
for f=2:15
r=randi(2,1,1);
if (position(f-1)==1)
position(f)=2;
elseif (position(f-1)==250)
position(f)=249;
elseif (r==1)
position(f)=position(f-1)+1;
else
position(f)=position(f-1)-1;
end
end
disp('Position = ');
disp(position);
plot(1:length(position),position)
xlabel('time')
ylabel('Position')
probability=abs(pos-position(length(position)))/15*100
%how do I make this entire code, that calculates for a number loop one
%million times and give the final convergent number.

採用された回答

Walter Roberson
Walter Roberson 2021 年 7 月 19 日
The system does not converge.
%I have code which includes a for and while loop which I have to loop one
%million times, to find a convergent output (probability).
iter = 1e3;
probability = zeros(1,iter);
N = 250;
sq = (1:N).^2;
prime = primes(N);
for K = 1 : iter
pos = randi(255,1,1);
position = zeros(1,15);
position(1) = pos;
for f=2:15
r=randi(2,1,1);
if (position(f-1)==1)
position(f)=2;
elseif (position(f-1)==250)
position(f)=249;
elseif (r==1)
position(f)=position(f-1)+1;
else
position(f)=position(f-1)-1;
end
end
% disp('Position = ');
% disp(position);
plot(position)
hold on
xlabel('time')
ylabel('Position')
probability(K) = abs(pos-position(end))/15*100;
end
%how do I make this entire code, that calculates for a number loop one
%million times and give the final convergent number.
probability(end-5:end)
ans = 1×6
0 53.3333 0 0 0 40.0000

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by