Assign separate handles to function outputs

조회 수: 5 (최근 30일)
Lukas Bystricky
Lukas Bystricky 2015년 8월 25일
편집: Matt J 2015년 8월 25일
I have a function that returns two outputs, the function value and its derivative. I'd like to create separate handles to the function value and the derivative. Is this possible?
For clarity, I'd like to do something like this:
function [f, fdx] = get_values(x)
...
end
f = @(x) get_values(x) %first output
g = @(x) get_values(x) %second output somehow, not sure how to do this

답변 (1개)

Matt J
Matt J 2015년 8월 25일
편집: Matt J 2015년 8월 25일
Create an additional function
function fdx=get_fdx(x)
[~,fdx]=get_values(x);
end
and now
f = @get_values%first output
g = @get_fdx %second output somehow, not sure how to do this
  댓글 수: 2
Walter Roberson
Walter Roberson 2015년 8월 25일
I agree. Notice that you need a real function for this, not an anonymous function. MATLAB does not provide any mechanism to access any function output other than the first except for the case that the output is being assigned to a location with "=". You cannot access the second output of a function from within an anonymous function.
Matt J
Matt J 2015년 8월 25일
편집: Matt J 2015년 8월 25일
If you return the arguments as structure fields,
function out = get_values(x)
....
out.f=f;
out.fdx=fdx;
end
then you can do things like,
f = @(x) getfield(get_values(x),'f') %first output
g = @(x) getfield(get_values(x),'dfx') %second output

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by