【问题标题】:Force the number of outputs from function call without setting output variables在不设置输出变量的情况下强制函数调用的输出数量
【发布时间】:2026-01-04 04:00:01
【问题描述】:

对于任何函数,我都可以通过明确定义我期望的输出数量来指定要返回的变量[out1,out2,...,outn] = ...

编辑:能够最大化潜在的输出数量也是有用的

示例问题

以下代码完全符合预期(是的,myArray(IND) = 1; 是多余的)

[I,J] = ind2sub(size(myArray),IND)
myArray(I,J) = 1;

当我尝试直接传递函数参数时,我没有得到我想要的结果

myArray(ind2sub(size(myArray),IND)) = 1;

当我想要myArray(I,J) = 1; 时,我实际上得到了myArray(I) = 1;

问题

如何在不明确定义输出参数的情况下指定返回多少输出变量?

我希望 eval() 系列中的某些功能或 [],{},(:), etc. 的某些类型转换可以解决问题,但我没有看到任何文档或让它们中的任何一个工作。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    直接使用ind2sub 的输出作为myArray 的索引而没有中间变量的直接问题是subsindex 在索引myArray 时仅请求ind2sub 的第一个输出。然后将第一个输出用作 linear index 以索引到 myArray 并分配导致您意外行为的值。

    相反,您可以根据需要使用cell array to capture as many outputs,然后依靠{} 索引来生成comma-separated list

    [outputs{1:ndims(myArray)}] = ind2sub(size(myArray), IND);
    

    然后您可以使用这个包含所有输出的元胞数组将所有值作为inputs or subscripts 转发到其他地方:

    myArray(outputs{:}) = 1;
    

    话虽如此,在您展示的示例中,您实际上不需要执行任何操作,因为您可以使用线性索引 IND 直接索引到 myArrayIn fact, using the output of ind2sub will likely give you the incorrect assignment as every permutation of the subscripts will be used when assigning values rather than the element-wise pairing of subscripts

    myArray(IND) = 1;
    

    一般情况下,您可以将此技术与nargout 一起使用来请求所有输出参数如果输出数量不可变

    [outputs{1:nargout('func')}] = func(inputs);
    

    【讨论】:

    • 啊,谢谢您,您已经强调了为什么需要为具有可变输出的内置函数进行显式输出定义。我希望有一个内联解决方案,它允许在没有变量分配的情况下进行显式输出定义(即 eval('foo(...),"nargout", 2') ),但我没有看到任何证据表明存在一个
    • @BrendanFrick 我很困惑。有。这是[outputs{1:2}] = thing
    • 你能称之为内联吗? foo1([outputs{1:2}] = foo2(...))
    • @BrendanFrick 不,您需要临时变量。我明白你现在指的是什么
    • @BrendanFrick 你读过我的全部答案了吗?您转发的输出不会产生正确的结果。查看链接的帖子
    最近更新 更多