0

I have a function that returns three values [A,B,C]=ABC(x).

Is it possible to define a function A(x) in an elegant way such that returns the first value of ABC(x), B(x) for the second value, etc.?

Thanks

foreignvol
  • 681
  • 2
  • 7
  • 15

3 Answers3

2

Not completely clear whether you really mean that ABC returns a vector, or that it returns three values (each of which might be any object). If you really mean "vector" with three elements, [A B C]. then you could do:

function a = A(x)
temp = ABC(x);
a = temp(1);
Floris
  • 45,857
  • 6
  • 70
  • 122
2

As you wrote your function ([A,B,C]=ABC(x)) it does not return a vector per say, it returns 3 values.

If you call your function like this

a = ABC(x)

a would be equal to A.

EDIT :

function b = B(x)
[~, b, ~] = ABC(x)
end
AdrienNK
  • 850
  • 8
  • 19
  • You're right but I also would like to obtain the second value. I edited the original post. Thanks. – foreignvol Mar 08 '14 at 19:40
  • 1
    You can also do [~, b, ~] = ABC(x) to get the second value. I don't really see why you want to have more functions. – AdrienNK Mar 08 '14 at 19:44
  • I want to define a second function F=@(y,z) A(x)*y+B(z). – foreignvol Mar 08 '14 at 19:52
  • This is a nice clean solution. It does require a "somewhat recent" version of Matlab -the `~` notation was introduced with R2009. See for example http://stackoverflow.com/a/747439/1967396 – Floris Mar 08 '14 at 22:13
0

You could include a 2nd input argument if it is acceptable to you. You could use varargin to accept variable number of input arguments.

function outValue=ABC(varargin);

if nargin==0
   error('Need at least one argument');
elseif nargin==1
   %obtain result
   outValue=result;
elseif nargin==2
   %obtain result
   outValue=result(index);
else
   error('Function accepts maximum of 2 arguments');
end

end
Autonomous
  • 8,935
  • 1
  • 38
  • 77