Haile
Haile

Reputation: 3180

How does the lu( ) function decide what to return?

Let A be the following matrix:

1 3 
2 4

if I call the lu( ) function and save the return values like this:

[L, U] = lu(A);

MATLAB returns L, U such that L * U = A:

>> L * U

ans =
     1     3
     2     4

While when I save the return values like this:

[L, U, P] = lu(A);

L * U is not equal to A:

>> L * U

ans =
     2     4
     1     3

because lu( ) returns L, U, P such that L * U = P * A

My questions:

Upvotes: 4

Views: 108

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 14939

Yes, this can be replicated using varargout. Similarly you can use varargin if you want variable number of inputs.

function varargout = my_fun(a,b,c);
   varargout{1} = b;
   varargout{2} = c;
   varargout{3} = a;
end

Now, this function can be called

x = my_fun(1,2,3)
x = 2

[x, y] = my_fun(1,2,3)
x = 2
y = 3

[x, y, z] = my_fun(1,2,3)
x = 2
y = 3
z = 1

As Sam Roberts points out, this does not help you create a function that behaves differently for different numbers of outputs. If that's what you want, you should check out nargout in combination with a switch-statement. Similarly, you can use nargin if you want to alter the behavior depending on the number of input variables. Please check out Sam Roberts' answer to see how this can be done.

Upvotes: 2

Sam Roberts
Sam Roberts

Reputation: 24127

You can use the nargout function to detect how many output arguments have been requested.

In addition, you can use varargout to fill your argument list appropriately.

For example:

function varargout = myfun(a,b)

    switch nargout
        case 1
            varargout{1} = a;
        case 2
            varargout{1} = b;
            varargout{2} = a;
    end

end

When called with one output argument, the first (and only) output will be a. When called with two, the first will be b, the second a.

You can also use nargoutchk (or in older versions nargchk) to assert that the number of output arguments requested is within specified limits.

lu does something similar to this, but is implemented in compiled C rather than MATLAB.

Upvotes: 3

Related Questions