# How to get a value from inside a function?

1 view (last 30 days)
I'm using the following function in my main program to calculate alpha_def:
alpha_def=fminbnd(@(alpha)fun_a(alpha, data_1, data_2, data_3, data_4, data_5, data_6), -alpha_0, alpha_0, options);
Inside of fun_a, I calculate beta_def the following way:
beta_def=lsqnonlin(@(beta)fun_b(beta, data_3, data_4, data_5, data_6), beta_0)
which is used to calculate alpha_def in fun_a.
After obtaining alpha_def, I need to use the value of beta_def in my main program. Is there a way of getting the value of beta_def from inside fun_a?
Thanks!

#### 1 Comment

Bjorn Gustavsson on 6 Feb 2020
No you dont. In your fminbnd call the anonymous function is independent of x and will just give an arbitrary result.
We might assume that you use:
alpha_def=fminbnd(@(x)fun_a(x, data_1, data_2, data_3, data_4, data_5, data_6), -alpha_0, alpha_0, options);
...but it might also be:
alpha_def=fminbnd(@(x)fun_a(alpha, data_1, data_2, data_3, data_4, x, data_6), -alpha_0, alpha_0, options);

Bjorn Gustavsson on 6 Feb 2020
So we know something about your functions, but not much more than the most general stuff. If you write your function fun_a something like this:
function varargout = fun_a(alpha,data1,data2,data3,data4,data5,data6,beta_out_too)
beta_0 = alpha-data1; % or something
beta_def=lsqnonlin(@(beta)fun_b(beta, data_3, data_4, data_5, data_6), beta_0);
val = sum((beta_def*alpha-data1./data2).^2);
varargout{1} = val;
if beta_out_too
varargout{2} = beta_def;
end
end
Then you can change the call to fminbnd to:
alpha_def=fminbnd(@(alpha)fun_a(alpha, data_1, data_2, data_3, data_4, data_5, data_6,0), -alpha_0, alpha_0, options);
% Then call fun_a again to get the beta_def-value you're interested in:
[val,beta_optimal] = fun_a(alpha_def, data_1, data_2, data_3, data_4, data_5, data_6,1);'
HTH