【问题标题】:How can I use indexing on the output of a function? [duplicate]如何对函数的输出使用索引? [复制]
【发布时间】:2011-10-15 22:01:10
【问题描述】:

可能重复:
How can I index a MATLAB array returned by a function without first assigning it to a local variable?

我想对函数的输出使用索引。我使用 textscan 功能来读取非常大的文本文件(15 GB)。在我的例子中,textscan 函数的返回是一个 1x1 元胞数组,其中包含一个非常大的数值数组。

而不是做:

tmp = textscan(...);
final_result = mat2cell(tmp{1,1});

我想做:

final_result = mat2cell( textscan(...){1,1} );

如果这可行,它将避免创建非常大的临时变量 tmp。还有其他方法可以避免临时变量吗?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    如果您仍然想知道,请考虑以下示例:

    %# some function that returns a cell array (TEXTSCAN in your case)
    myFunc = @() {rand(5,5)};
    
    %# normally you would write
    C = myFunc();
    C = C{1,1};
    

    这是链接问题中@gnovice 答案的单元阵列版本(丑陋但有效):

    %# equivalent to: C = myFunc(){1,1}
    C = subsref(myFunc(), struct('type','{}','subs',{{[1 1]}}))
    

    【讨论】:

      【解决方案2】:

      您不能像您展示的那样直接索引函数的输出。您可以做的是将您的代码更改为以下内容:

      final_result = textscan(...);
      final_result = mat2cell(final_result{1,1});
      

      元胞数组的每个元素都包含指向其他 mxArray 的指针。因此,当从元胞数组中提取数据时,可以简单地让输出 mxArray 指向相同的数据。使用 final_result 变量来保存元胞数组以及从中提取的内容可能足以告诉 MATLAB JIT 它可以通过不制作中间副本来优化代码。

      【讨论】:

        猜你喜欢
        • 2021-06-24
        • 2018-06-30
        • 2021-02-13
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多