How to get a value from inside a function?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Bjorn Gustavsson
2020-2-6
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
2020-2-6
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
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!