【问题标题】:Saving return values of function returning multiple variables in Matlab在Matlab中保存返回多个变量的函数的返回值
【发布时间】:2013-04-26 03:53:43
【问题描述】:

我以前从未使用过matlab,所以请原谅这个非常基本的问题。

基本上我有一个返回多个变量的函数,定义如下:

function [a, b, c]=somefunction(x, y, z)

我知道我可以得到如下返回值:

[a,b,c] = somefunction(1,2,3);

现在我想做的是将多次运行的somefunction 保存到一个数组中,然后再检索它们。我试过了:

results = [];
results = [results somefunction(1,2,3)];
results = [results somefunction(4,5,6)];

然后我尝试访问单个运行:

% access second run, i.e. somefunction(1,2,3) ?
a = results(2, 1);
b = results(2, 2);
c = results(2, 3);

但这告诉我索引超出范围,因为size(results) = [1,99654](99654 是我需要保存的结果数)。所以它似乎不是一个数组?对不起这个基本问题,我从来没有使用过matlab。

【问题讨论】:

    标签: arrays matlab function indexing


    【解决方案1】:

    当您将数组与[ ... ] 组合在一起时,您会将它们连接起来,从而创建一个长的扁平数组。例如,如果调用 1 返回 3 个元素,调用 2 返回 8 个元素,调用 3 返回 4 个元素,则最终将得到一个 14 长的数组,并且无法知道哪些元素来自哪个函数调用。

    如果您想将每次运行的结果分开,您可以将它们存储在一个元胞数组中。您仍然需要在 LHS 上使用逗号分隔的列表来获取所有多个参数。 {}-indexing 语法与 () 不同,“弹出”内容进出单元格元素。

    让我们将结果存储在一个名为 x 的 k×n 数组中,其中函数返回 n 个输出,我们将调用它 k 次。

    x = cell(2, 3); % cell(k, n)
    % Make calls
    [x{1,1}, x{1,2}, x{1,3}] = somefunction(1,2,3);
    [x{2,1}, x{2,2}, x{2,3}] = somefunction(4,5,6);
    % Now, the results of the ni-th argout of the ki-th call are in x{ki,ni}
    % E.g. here is the 3rd argout from the second call
    x{2,3}
    

    您还可以将 argouts 存储在单独的变量中,这样可能更具可读性。在这种情况下,每个都是一个 k 长向量

    [a,b,c] = deal(cell(1,2));  % cell(1,k)
    [a{1}, b{1}, c{1}] = somefunction(1,2,3);
    [a{2}, b{2}, c{2}] = somefunction(1,2,3);
    

    当然,如果您的 somefunction 输入符合此要求,则这可以推广到循环。

    [a,b,c] = deal(cell(1,nIterations));
    for k = 1:nIterations
        [a{k}, b{k}, c{k}] = somefunction(1,2,3);
    end
    

    详细信息在http://www.mathworks.com/help/matlab/cell-arrays.htmldoc cell 的文档中。

    (旁注:您帖子中的 results(1, 2) 对于大小为 [1,99654] 的数组应该会成功。确定您没有这样做 results(2, 1)?)

    【讨论】:

    • 谢谢!是的,是 results(2, 1) 失败了,不是另一个,现在修复了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2018-05-10
    • 2016-06-29
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多