匿名函数调用具有多种输出形式的函数 [英] Anonymous functions calling functions with multiple output forms

查看:94
本文介绍了匿名函数调用具有多种输出形式的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个匿名函数,该函数调用返回多个输出的函数版本.

I'm trying to define an anonymous function that calls a version of a function that returns multiple outputs.

例如,函数find具有两种可能的输出形式:

For example, the function find has two possible output forms:

[row,col] = find(X);

[ind] = find(X);

说我想在匿名函数中选择第一种形式.

Say I would like to choose the first form inside of an anonymous function.

我尝试过 1)

get_columns = @(x) x(2);

2)

get_columns = @(x,y) y;

但是当我打电话时:

get_columns(find(x))

get_columns的第一个版本认为我将find称为[ind] = find(X)而不是[row,col] = find(X);,而第二个版本则抱怨"Not enough input arguments".

The first version of get_columns thinks I am calling find as [ind] = find(X) and not as [row,col] = find(X);, while the second one complains with "Not enough input arguments".

是否可以触发内部匿名功能中的功能的特定输出形式?

Is there a way to trigger a specific output form of a function inside an anonymous function?

推荐答案

直接,不.不幸的是,有许多功能无法通过匿名函数访问,而访问多个输出参数就是其中之一. (我经常发现的另一个问题是,您无法在匿名函数内定义if语句.这似乎是Matlab语法的局限性.

Directly, no. Unfortunately, there are a number of features which are inaccessible via anonymous functions, and accessing multiple output arguments is one of them. (The other one I frequently find is that you cannot define an if statement inside an anonymous function. This appears to be a limitation of Matlab syntax more than anything else.

但是,非常简单的辅助函数可以实现这一点.

However, a pretty simple helper function can make this possible.

function varargout = get_outputs(fn, ixsOutputs)
output_cell = cell(1,max(ixsOutputs));
[output_cell{:}] = (fn());
varargout = output_cell(ixsOutputs);

此函数带有一个函数句柄以及一个输出索引数组,并返回已索引的输出.

This function takes a function handle plus an array of output indexes, and returns the indexed outputs.

如果创建此文件(希望注释更好)并将其放在路径上,则可以通过定义以下函数来访问find函数的第二个输出

If you create this file (hopefully better commented) and put it on your path, then you can access the second output of the find function as by defining the following function

find_2nd = @(x)get_outputs(@()find(x),2)

现在您可以找到等于1的数组的索引.

And now you can find the find the indexes of an array which equal 1 as

>> find_2nd([4 3 2 1]==1)
ans =
    4

现在您应该能够从匿名函数中随意访问其他输出参数.

And now you should be able to access alternative output arguments at-will from within anonymous functions.

这篇关于匿名函数调用具有多种输出形式的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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