2012-11-07 97 views
2

所以我有這個奇怪的問題,我不明白。 我有一個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 

感謝您的幫助

回答

1

並不進入語義,這裏是你在做什麼:

第1步:你調用一個函數試驗....改變d,直到你得到一個期望值。

步驟2:再次調用試驗,但保持與以前相同。它是否符合之前的最終條件?是。停止試驗

第3步:再次調用試驗,但保持與先前使用的d相同。它是否符合之前的最終條件?是。停止試驗

第4步:再次呼叫試驗,但保持與先前使用的d相同。它是否符合之前的最終條件?是。在Trials功能重新初始化d

:停止試驗

解決方案

function s=Trials() 
    d=0; 
    s=0; 
... 
0

我同意你的s和d變量的重新初始化。您發現難以調試的原因是您正在使用全局變量。除非你絕對必要,否則請不要這樣做!

這裏是沒有全局變量的一個版本:

function foo() 
N   = 10; 
Tup   = 10; 
Tdown  = -10; 
StepLength = 1; 
d   = 0; 
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 
    for i_trial= 1:N 
     S(i_trial) = Trials(Tdown, Tup, StepLength, StepLimit); 
    end 
end 

x   = 0:10:max(S); 
hist(S,x); 
axis tight; 
xlabel('Number of Steps'); 
ylabel('Number of Trials'); 

function s=Trials(Tdown, Tup, StepLength, StepLimit) 
s = 0; 
d = 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; 

你爲什麼要在主函數中使用while循環(我已經打破你的代碼與for循環)?