2012-07-11 42 views
0

目前我在Secant方法上做了一個代碼,到目前爲止代碼運行正常。 但是,我仍然需要通過計算我在「割線」函數中使用的函數調用數來更新我的「count.funcCount」。我應該如何修改我的代碼?MATLAB - 如何計算函數調用次數

這是我到目前爲止的代碼:

function [ root, fcneval, count ] = secant(f, x0, x1, my_options) 
my_options = optimset('MaxIter', 50, 'TolFun', 1.0e-5); 
count = struct('iterations',0,'funcCount',0,'message',{'empty'}); 
xp = x0; %# Initialize xp and xc to match with 
xc = x1; %# x0 and x1, respectively 
MaxIter = 100; 
TolFun = 1.0e-5; 

%# Secant Method Loop 
for i = 2:MaxIter 
    fd = f(xc) - f(xp); %# Together, the ratio of d and fd yields 
    d = xc - xp; %# the slope of the secant line going through xc and xp 
    xn = ((xc * fd) - (f(xc) * d))/fd; %# Secant Method step 

    if (abs(xc - xn) < TolFun) && (abs(f(xn)) < TolFun) %# Stopping condition 
     break; 
    elseif i > MaxIter %# If still can't find a root after maximum 
         %# 100 iterations, consider not converge 
     count.message = sprintf('Do not converge'); 
    end 

    xp = xc; % Update variables xc and xp 
    xc = xn; 
end 

%# Get outputs: 
root = xn; 
fcneval = f(root); 
count.iterations = i; 
end %# end function 

--------------------------------------- 
function [f] = fun(x) 
f = cos(x) + x; 
end 

請幫幫我,謝謝你提前

+3

你知道了Matlab'profile'命令不好嗎? – 2012-07-11 06:21:28

+0

函數調用什麼?任何事情?你最終的目標是什麼? – Dan 2012-07-11 07:10:45

+0

使用profiler,Luke! – 2012-07-11 08:38:42

回答

0

雖然我不明白你的問題,但我仍然認爲你可以使用一個計數器。用零初始化它,並在每次調用函數時增加它。您正在使用內置函數,只需對其源代碼進行必要的更改(僅供參考:您可以在matlab中執行此操作),然後將其保存爲新名稱,然後在主代碼中使用它。

0

您可以創建一個可訪問其父功能變量(包括功能f和計數器count.funcCount)的嵌套函數。這個函數會調用計算的實際方法,然後增加計數器。

這是一個相當愚蠢的例子來說明這一概念:

function [output,count] = myAlgorithm(f, x0) 
    count = 0; 
    output = x0; 
    while rand()<0.99   %# simulate a long loop 
     output = output + fcn(x0); 
    end 

    %# nested function with closure 
    function y = fcn(x) 
     %# access `f` and `count` inside the parent function 
     y = f(x);    %# call the function 
     count = count + 1; %# increment counter 
    end 
end 

現在你罵它:

[output,count] = myAlgorithm(@(x)cos(x)+x, 1)