如何强制MATLAB返回嵌套函数调用中的所有值? [英] How to force MATLAB to return all values in a nested function call?

查看:342
本文介绍了如何强制MATLAB返回嵌套函数调用中的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,假设函数是一个函数, foo 返回三个完全相同大小的列向量。说:
$ b $ pre $ 函数[a,b,c] = foo(n)
a = rand(n,1) ;
b = rand(n,1);
c = rand(n,1);
end

现在,假设 bar 是一个函数,可以输入一个大小(1,3)的单元数组。 > function result = bar(triplet)
[x,y,z] = triplet {:};
result = x + y + z;
end

如果我想传递 foo( 5),我可以通过创建三个无用的变量来完成它:

  [x,y ,z] = foo(5); 
result = bar({x,y,z});

是否有一些函数 baz 允许(baz(foo(5)));我将上面的两行替换为

  result = bar 



注意:上面的code> foo 和 bar 仅作为示例。他们应该代表我无法控制的功能。 IOW,修改它们不是一个选项。

解决方案

不可能。 baz(foo(5))中的 baz 将仅接收 foo ,其他两个将被忽略。简单的两线变体并不那么尴尬。这不是一个普遍的情况。你通常不用普通数组数组会做的单元阵列。



你当然可以为 foo 编写自己的包装器, code>返回你需要的任何东西(即包含类似的两行),以防你需要经常使用它。


I find it impossible to write MATLAB code without creating a huge number of superfluous, single-use variables.

For example, suppose function foo returns three column vectors of exactly the same size. Say:

function [a, b, c] = foo(n)
    a = rand(n, 1);
    b = rand(n, 1);
    c = rand(n, 1);
end

Now, suppose that bar is a function that expect as imput a cell array of size (1, 3).

function result = bar(triplet)
    [x, y, z] = triplet{:};
    result = x + y + z;
end

If I want to pass the results of foo(5), I can do it by creating three otherwise-useless variables:

[x, y, z] = foo(5);
result = bar({x, y, z});

Is there some function baz that would allow me to replace the two lines above with

result = bar(baz(foo(5)));

?

NB: the functions foo and bar above are meant only as examples. They're supposed to represent functions over which I have no control. IOW, modifying them is not an option.

解决方案

Not possible. baz in baz(foo(5)) will only take the first output of foo, the other two would be ignored. The plain two-line variant is not that awkward. And this is not a common situation. You don't generally work with cell arrays where normal numerical arrays would do.

You could of course just write your own wrapper for foo that returns whatever you need (i.e. containing similar two lines), in case you need to use it frequently.

这篇关于如何强制MATLAB返回嵌套函数调用中的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆