MATLAB函数的返回值是否取决于它的调用方式?

时间:2010-04-06 17:08:06

标签: matlab function

A = imread(filename, fmt)

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

以上是imread的概要部分,似乎说MATLAB函数的返回值取决于它的调用方式?这是真的吗?

2 个答案:

答案 0 :(得分:4)

IMREAD功能定义为

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

在您的2个示例中,A和X将是相同的,但在第二种情况下,将有其他变量map

如果在函数定义中使用VARARGOUT,MATLAB中有一种方法可以定义变量输出:

function varargout = foo(x)

因此,您可以根据函数体中的某些条件输出不同的值。

这是一个愚蠢的例子,但它说明了概念:

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

然后

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

输出参数甚至可以是不同的数据类型。

另一个基于输出变量数量的条件示例:

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

然后

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

答案 1 :(得分:3)

是的,matlab有一种机制可以提供可变数量的结果,也可以提供输入参数。

您可以在编写函数时自己使用它,请参阅Mathwork上有关narg*的文档以了解更多信息。

histogram函数

为例
> 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