# How to define a function with multiple handle in a loop?

5 views (last 30 days)
Md Nurul Anwar on 11 Sep 2022
Commented: Md Nurul Anwar on 15 Sep 2022
I have a situation where I need to use a function that can take different number of input (depnding upon the number of treatment considered).
The function has a general expression (Attached as Pic for readability)
Currently I am defining the function (for different number of treatment) seperately (as bellow)
%% Parameters
par.a=80/365;% %; %bitting frequiency (per day)
par.g=1/10; %mosquito death rate (per day)
par.n=12; %duration of sporogony in mopsquito
par.b=.5; %transmission probability: mosquito to human
par.c=.23; %transmission probability: human to mosquito
par.r=1/60; %rate of blood stage infection clearance
par.omega=1/425 ; %hypnozoites death rate
par.nu=8.5; %Number of hypnozoites per infection
par.alpha=1/332;%1/332;
p_blood=.9; %treatment effect
% tau is the current time
% s1,s2,s3 are treatment time.
pA=@(tau) par.alpha*(exp(-par.r*tau)-exp(-(par.alpha+par.omega)*tau))/(par.alpha+par.omega-par.r); %Base function without treatment
as I couldn't figure out how to define these in a single function. The main issue is that as the number of treatment increases, the function handle increases as well and the function with larger handles utilise the function with lower handles for different inputs (as is attached pic). This is making me crazy. Is there any way that I can define these in a loop or nested function? Any help is much appreciated.

Jan on 11 Sep 2022
Is there a need to use an anonymous function? Why not writing a standard function?
function y = pA(tau, s1, s2, s3)
a=80/365;% %; %bitting frequiency (per day)
g=1/10; %mosquito death rate (per day)
n=12; %duration of sporogony in mopsquito
b=.5; %transmission probability: mosquito to human
c=.23; %transmission probability: human to mosquito
r=1/60; %rate of blood stage infection clearance
omega=1/425 ; %hypnozoites death rate
nu=8.5; %Number of hypnozoites per infection
alpha=1/332;%1/332;
p_blood=.9; %treatment effect
% tau is the current time
% s1,s2,s3 are treatment time.
y0 = alpha*(exp(-r*tau)-exp(-(alpha+omega)*tau))/(alpha+omega-par.r);
switch nargin
case 1
y = y0; %Base function without treatment
case 2
y = (1-p_blood)*exp(-r*(tau-s1)).*pA(s1)+(1-p_rad)*(y0-exp(-r*(tau-s1)).*pA(s1)); %with one treatment
case 3
y = (1-p_blood)*exp(-r*(tau-s2)).*pA(s2,s1)+(1-p_rad)^2*(y0-exp(-r*(tau-s2)).*pA(s2)); %with two treatment
case 4
otherwise
error('Too many inputs');
end
end
Md Nurul Anwar on 15 Sep 2022
It works! Thanks a lot Jan.

### Categories

Find more on System Composer in Help Center and File Exchange

R2021a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by