所以我有這個奇怪的問題,我不明白。 我有一個while循環根據索引將值傳入向量。這些值由一個被調用的子函數提供。我的問題是,在第一次迭代之後,矢量不再接受來自子函數的值,儘管代碼保持運行並且不會中斷。 這發生在'S(i)=試驗;'。用子函數調用奇怪'while'循環行爲(MATLAB)
function Simulation()
N=input('How many trials would you like to run? ');
Tup=input('What is the positive boundary? ');
Tdown=input('What is the negative boundary? ');
StepLength=input('What is the step length? ');
d=0;
i=1;
S=zeros(1,N);
StepLimit=1000000;
if Tup==Tdown
display('Please use boundaries that are not equal to eachother.');
elseif Tup<=d||Tdown>=d
display('Please choose logical boundaries.');
else
while i<=N
S(i)=Trials;
i=i+1;
end
end
x=0:10:max(S);
hist(S,x);
axis tight;
xlabel('Number of Steps');
ylabel('Number of Trials');
function s=Trials()
s=0;
while ~(d<=Tdown)&&~(d>=Tup)
m=StepLength.*RandDir(1);
d=d+m;
s=s+1;
if s>=StepLimit
display('The step limit was reached.');
return
end
end
function out = RandDir(N)
% Generate a random vector from the set {+/- e_1, +/- e_2,..., +/- e_N}
% where e_i is the ith basis vector. N should be an integer.
I = round(ceil(2*N*rand));
if rem(I,2) == 1
sgn = -1;
else
sgn = 1;
end
out = zeros(N,1);
out(ceil(I/2)) = sgn*1;
end
end
end
感謝您的幫助