function函数嵌套 matlab_如何强制MATLAB返回嵌套函数调用中的所有值?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值