Any way to simultaneously solve 2 functions where the output of one is the input of another to avoid undefined variable error?

2 views (last 30 days)
Hi All. I'm having a little trouble evaluating B in the function bidfn which involves finding the zeroes of the output of a nested function. More specifically, the output of bidfn is a function of stfna, but stfna takes the output of bidfn as an input argument. Trying to solve this leads to an error.
Just for some context, Dmr is the numerical solution to a first-order differential equation at the 101 points in A. srfna and stfna are my attempts to find sr and st in x=K(sr) and B=RR(st) respectively.
My problem is that B is the output of bidfn, which depends on stfna, which takes B as an input. This means that before I can solve for B in bidfn I have to specify B in stfna. How can I possibly solve for B and use B as input argument at the same time? Anytime I try to evaluate bidfn for a given x I get the following error:
Undefined function or variable "B".
Error in bidfn/stfna (line 72)
if B<=RR(1)
Error in bidfn (line 15)
st=stfna;
Now, I understand where this error comes from any why it occurs, that is not my problem. The part I need help with is writing the code in such a way as to avoid this problem altogether. What I'm asking is whether anyone may be able to rewrite/give me some advice about rewriting my code so that I can actually solve for B in bidfn? For example, is there are way to simultaneously solve bidfn and stfna to avoid the error?
Thanks in advance.
This is my code:
function B=bidfn(x)
%%%DEFINITIONS
K=Dmr; % this is the solution to the ODE dmr/ds
A=0:0.01:1; % this is the set of points K is solved at
for i=1:101
RR=A+K; % this function combines the two
end
%%%FUNCTION CALLS
fun=@ptesta;
sr=srfna;
st=stfna;
%%%B FUNCTION
if x<0.5
B=0;
elseif x==0.5
B=0.5;
elseif x>=0.5+K(101)
B=x+0.5;
else
x0=[0,1];
B=fzero(fun,x0);
end
%%%NESTED FUNCTIONS
%%%Nested function 1
function C=ptesta
for y=1:101
z1=integral(A(y)+x,0,sr(y));
z2=integral(RR(y),st(y),sr(y));
C=(z1-z2)-B*st(y);
end
end
%%%Nested function 2
function sr=srfna
if x<=K(1)
sr=0;
elseif x>=K(101)
sr=1;
else
for q=2:100
if x>=K(q-1) && x<K(q)
sr=A(q-1);
end
end
end
end
%%%Nested function 3
function st=stfna
if B<=RR(1)
st=0;
elseif B>=RR(101)
st=1;
else
for v=2:100
if B>=RR(v-1) && B<RR(v)
st=A(v-1);
end
end
end
end
%%%END OF NESTED FUNCTIONS
end

Answers (0)

Community Treasure Hunt

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

Start Hunting!