I would like to calculate the following function efficiently, and therefore preferably with a function handle.
In the given equation only "s" is the variable. The rest are some known constants but they are changing inside the loop. I would like to obtain this as a function handle because later I need to find the roots of this function.
This question is related to this one which I asked recently. But the answer seems to be inefficient and I am not able to obtain a single function handle for this whole thing. Is there any way?
My trial:
K=10;
N=4;
for ii=1:K
for jj=1:N
f{ii,jj}=@(x) p_th0{ii}(jj).*log(p_th1{ii}(jj)/p_th0{ii}(jj)).*(p_th1{ii}(jj)/p_th0{ii}(jj)).^x;
end
end
function y = sum_of_functions(f,x)
y = 0;
for ii=1:numel(f)
y = y + f{ii}(x);
end
end
r = FindRoots(@(x)sum_of_functions(f,x),A,B,2^5,0);
In this code "x" (corresponding to "s" in the formula) is the variable for which the roots are later found. "p_th0" and "p_th1" are cells of some known constants (changing inside outer while loop). In the code above this part f{ii,jj}=@(x) is missing the term to which we need to divide the sum. So it only considers double sum over the numerator in the given figure.
I also need to note that, I am unhappy about not having a single function handle for the whole thing. What I have is just a cell with some functions and for every time I need to evaluate the sum, I must build the sum first. Instead I would want to build the sum of the function handle once and just use this function handle in "FindRoots".