Additional output with fsolve

I'm asking what seems to be an identical question to this one. Specifically, I simply want to output additional variables after fsolve completes its task. Suppose that I am using fsolve with this function:
function [F G] = myfunc(x)
F = x^2;
G = 2;
I will be using fsolve with
xsol = fsolve(@(x)myfunc(x), guess);
This will give me the solution. However, if I want the value of G, I need to call myfunc again
[F, G] = myfunc(xsol)
I'd like to NOT evaluate myfunc again. How do I get fsolve to also output additional variables? I'd like to do so without global variables or outputting to files...

 채택된 답변

Andrew Newell
Andrew Newell 2011년 5월 14일

1 개 추천

Is the G you're really calculating costly to evaluate? If so, I'd suggest a different approach. Define your function as
function [F G] = myfunc(x)
F = x^2;
if nargout > 1
G = 2;
end
so it doesn't evaluate G during the solving (which would involve, generally, several calls to myfunc ). Note that you can use a more compact notation:
xsol = fsolve(@myfunc,guess);
Then go ahead and calculate G once:
[F G] = myfunc(x)
You'll probably save a lot more computation with this approach.

댓글 수: 2

Theo
Theo 2011년 5월 14일
I'm sorry I was not more specific (I tried to simplify the problem as much as I could).
> Is the G you're really calculating costly to evaluate?
Sort of. But it is also needed to determined F (and hence for fsolve). Think of G is a function and F as its norm (or some other property). Thus, fsolve will solve for G as it solves F = 0.
Andrew Newell
Andrew Newell 2011년 5월 14일
I do appreciate your obvious effort to distill the essence of this problem.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrew Newell
Andrew Newell 2011년 5월 14일

1 개 추천

Based on your comments, here is another approach. Define a function
function G = myGfunc(x)
persistent G
if nargin > 0
% calculate G
end
This saves the value of G you calculate. Then define
function [F G] = myfunc(x)
G = myGfunc(x);
F = GtoF(G); % Your method of calculating F using G
After your run, you can enter
G = myGfunc;
and it will simply return the saved value of G.
Caveat: it would be wise to enter
clear functions
before each run to make sure that G isn't saved from a previous run.

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

태그

질문:

2011년 5월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by