简体   繁体   中英

MATLAB - how to count the number of function calls

Currently I'm doing a code on the Secant Method, and so far the code runs ok. However, I still have to update my "count.funcCount" by counting the number of function calls that I used in the "secant" function. How should I modify my code ?

This is what I have so far for the code:

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

Please help me, thank you in advance

Although I did not understand your question but still I think you can use a counter. Initialize it with zero and increment it every time your function is called. You are using an inbuilt function, just make necessary changes in its source code( FYI :you can do this in matlab) then save it with a new name and then use it in your main code.

You could create a nested function which have access to the variables of its parent function (including the function f and the counter count.funcCount ). This function would call the actual method which does the computation, and then increment the counter.

Here is a rather silly example to illustrate the concept:

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

Now you call it as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM