【问题标题】:Does the return value of a MATLAB function depend on how it's called?MATLAB 函数的返回值是否取决于它的调用方式?
【发布时间】:2010-04-06 17:08:05
【问题描述】:
A = imread(filename, fmt)

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

以上在imread的synopsis部分,好像是说一个MATLAB函数的返回值取决于它是怎么调用的?这是真的吗?

【问题讨论】:

    标签: matlab function


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      是的,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
      

      【讨论】:

      • 让我确认一下,即使对于相同的输入参数,返回值是否真的可以不同?我从未在任何其他语言中看到过这样的功能。
      • 是的,这是真的。如果有帮助,您可以将结果列表视为一种特殊的参数。
      • 这个功能的名称是什么?我需要它来谷歌以获取更多信息:)
      • 谷歌搜索可变参数。但请注意,imread 并非如此。
      • @user198729:这是一个可能有用的链接:mathworks.com/access/helpdesk/help/techdoc/matlab_prog/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2021-08-20
      • 1970-01-01
      • 2015-07-26
      相关资源
      最近更新 更多