How to get a value from inside a function?

조회 수: 3 (최근 30일)
Ana Paula Pagnoncelli
Ana Paula Pagnoncelli 2020년 2월 6일
답변: Bjorn Gustavsson 2020년 2월 6일
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
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
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개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by