views:

61

answers:

2
A = imread(filename, fmt)

[X, map] = imread(...)

The above is in the synopsis part of imread, which seems to say that the return value of a MATLAB function depends on how it's called? Is that true?

+3  A: 

Yes, matlab has a mechanism to provide variable amount results, and also for the input parameters.

You can use it yourself when you write functions, see the documentation about narg* on Mathwork to learn more.

Take for example the histogram function

> hist(1:100); % generates a plot with the 10 bins
> hist(1:100, 4); % generates a plot with 4 bins
> fillrate = hist(1:100, 4); % returns the fill rate for the 4 bins
> [fillrate, center] = hist(1:100,4); % returns the fill rate and the bins center in 2 differen variables
Davy Landman
Let me confirm,is it true the return value can be different even for the same input parameters?I've never seen such a feature in any other languages yet.
Yep, that is true. If it helps, you can think of the results list as a special kind of argument.
perimosocordiae
What's the name of this feature?I need it to google for more info:)
Google for varargout. But note this is not the case for imread.
yuk
This is also the case in Perl, to some extent - you can google around for `wantarray` and context.
dsolimano
@user198729: Here's a link that may be useful: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/bresuxt-1.html
gnovice
@yuk ,why it is not the case for imread?
It's by function definition. See my answer.
yuk
+3  A: 

IMREAD function is defined as

function [X, map, alpha] = imread(varargin)

In your 2 examples A and X will be the same, but in the second case there will be additional variable map.

There is a way in MATLAB to define variable output if you use VARARGOUT in function definition:

function varargout = foo(x)

So you can output different values based on some condition in the function body.

This is a silly example, but it illustrates the consept:

function varargout = foo(a,b)
if a>b
    varargout{1} = a+b;
    varargout{2} = a-b;
else
    varargout{1} = a;
    varargout{2} = b;
end

Then

[x,y] = foo(2,3)
x =
     2
y =
     3
[x,y] = foo(3,2)
x =
     5
y =
     1

The output arguments can be even different data types.

Another example with condition based on number of output variables:

function varargout = foo(a,b)
if nargout < 2
    varargout{1} = a+b;
else
    varargout{1} = a;
    varargout{2} = b;
end

Then

[x,y] = foo(2,3)
x =
     2
y =
     3
x = foo(2,3)
x =
     5
yuk
Very nice explanation.
Jonas

related questions