Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Thread Subject:
How to count (and display) the number of function calls used in a function ??

Subject: How to count (and display) the number of function calls used in a function ??

From: Nhi

Date: 10 Jul, 2012 16:24:14

Message: 1 of 1

Hello everyone,
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, so that at the part where I use to "get outputs", I just can use
count.funcCount = something ???
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 % Begin counter, start from i = 2
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
elseif i > MaxIter % If still can't find a root after maximum
                           % 100 iterations, consider not converge
count.message = sprintf('Do not converge');
xp = xc; % Update variables xc and xp
xc = xn;
 end % end loop

%%%%%% Get outputs:
root = xn;
fcneval = f(root);
count.iterations = i;
 end % end function
function [f] = fun(x)
f = cos(x) + x;

Thank you very much.

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us