2012-07-11 905 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)