开发者

Does the return value of a MATLAB function depend on how it's called?

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 开发者_StackOverflowfunction depends on how it's called? Is that true?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜