2013-10-17 32 views
0

是否可以在文件函數定義文件中調用函數?我很好奇它。感謝您的回答。Octave:在函數文件中調用函數

%It would prove efficient to write a function since we are going 
%to do the same thing twice. 
function fleas(N); 
clear totalflea; 
%The below vector is for plotting purposes only. 
Nvector = linspace(0, N, N + 1); 
%Define the flea vector as follows: 
%The value 0 correspond to a fleas residing on dog B 
%(Burnside);thus initially all fleas are on Burnside. 
totalflea(1) = 0; 
%Since initially we do not have any fleas on Burnside. 
fv = zeros(1,50); 
for n = 1 : N; 
k = randi(50); 
%The above code generates a random integer between 1 and 50. 
%The code has been implemented in Octave 3.4. 
switch fv(k) 
    case 0 
    fv(k) = 1; 
    case 1 
    fv(k) = 0; 
end 
%The above statement changes the values of fv(k) depending 
%on its initial value. The possible values are 0 or 1. 
totalflea(n + 1) = sum(fv); 
endfor 
%The following lines are there to depict two standard deviations away 
%from the mean value of 25. The standard deviation of a discrete binomial 
%variable is found in "Introduction to Probability" by Bertsekas and 
%Tsitsiklis. The 2 SD barrier is as follows: 
sdp = ones(1, N + 1)*(25 + 2*sqrt(50)/2); 
sdm = ones(1, N + 1)*(25 - 2*sqrt(50)/2); 
plot (Nvector, totalflea, Nvector, sdp , "1", Nvector, sdm, "1"); 
% "1" is supplied as an optional argument to determine the color 
%of the graph. 
xlabel('Time Steps') 
ylabel('Fleas on Anik') 
xrange 
endfunction 

這工作得很好,但是當我附上例如跳蚤行(500),在文件的最後,我得到一個解析錯誤。當我在文件的開頭添加它時,出現以下錯誤:

warning: function 'fleas' defined within script file '/home/ongun/Desktop/Dropbox/Computational Physics/Codes/fleas.m' 
error: invalid use of script /home/ongun/Desktop/Dropbox/Computational Physics/Codes/fleas.m in index expression 

回答

3

在倍頻程中,您可以創建函數文件或腳本文件。我將簡化一點:

對於每個函數都要創建一個具有相同名稱的文件。以function ...結尾endfunction

如果要調用函數,可以使用命令行或創建腳本文件。腳本文件不包含任何函數定義,只需編寫要執行的命令即可。

因此,您必須創建第二個包含fleas(500)的文件或從命令行調用它。

+0

它已經在我目前的工作目錄中。當我通常調用這個函數的時候,然而,我想調用函數聲明文件中的函數,並且我得到的錯誤是第31行附近的解析錯誤,其中行號是相應的行。 – Vesnog

+0

什麼錯誤信息?你能發佈你的代碼嗎? – Daniel

+0

我已經發布了我的代碼。感謝您的關注。 – Vesnog