如何在多维数组上使用any()?
我正在测试一个任意大小、任意维度的逻辑数组,并且我想知道其中的一个或多个是否为真。 any()
一次仅适用于单个维度,sum()
也是如此。 我知道我可以测试维度数并重复 any()
直到得到一个答案,但我想要一种更快、更坦率、更优雅的方法。
有想法吗?
我正在运行 2009a(R17,我认为是旧说法)。
I'm testing an arbitrarily-large, arbitrarily-dimensioned array of logicals, and I'd like to find out if any one or more of them are true. any()
only works on a single dimension at a time, as does sum()
. I know that I could test the number of dimensions and repeat any()
until I get a single answer, but I'd like a quicker, and frankly, more-elegant, approach.
Ideas?
I'm running 2009a (R17, in the old parlance, I think).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如所指出的,正确的解决方案是将结果重塑为向量。 然后任何都会给出所需的结果。 因此,
any(A(:))
给出全局结果,如果任何 numel(A) 元素为 true,则为 true。 您还可以使用
任何(reshape(A,[],1))
显式使用重塑运算符。 如果您不想执行将矩阵转换为向量的额外步骤来应用任何矩阵,那么另一种方法是编写您自己的函数。 例如,这里有一个函数可以为您完成此操作:
========================
function result = myany(A)
% 确定是否有任何元素A 中的结果为非零
= any(A(:));
======================
将其另存为搜索路径上的 m 文件。 MATLAB 的优点(适用于任何编程语言)在于它是完全可扩展的。 如果您希望它具有某些功能,只需编写一个小惯用语即可实现它。 如果您经常这样做,您就会定制环境来满足您的需求。
As pointed out, the correct solution is to reshape the result into a vector. Then any will give the desired result. Thus,
any(A(:))
gives the global result, true if any of numel(A) elements were true. You could also have used
any(reshape(A,[],1))
which uses the reshape operator explicitly. If you don't wish to do the extra step of converting your matrices into vectors to apply any, then another approach is to write a function of your own. For example, here is a function that would do it for you:
======================
function result = myany(A)
% determines if any element at all in A was non-zero
result = any(A(:));
======================
Save this as an m-file on your search path. The beauty of MATLAB (true for any programming language) is it is fully extensible. If there is some capability that you wish it had, just write a little idiom that does it. If you do this often enough, you will have customized the environment to fit your needs.
如果您的数据位于矩阵A中,请尝试以下操作:
编辑:要为不熟悉语法的人提供更多解释,A(:) 使用 冒号运算符 获取整个内容数组 A 的大小,无论维度是什么,并将它们重新整形为单个列向量(大小为 numel(A)-by-1)。 只需调用一次 ANY 即可对得到的列向量。
If your data is in a matrix A, try this:
EDIT: To explain a bit more for anyone not familiar with the syntax, A(:) uses the colon operator to take the entire contents of the array A, no matter what the dimensions, and reshape them into a single column vector (of size numel(A)-by-1). Only one call to ANY is needed to operate on the resulting column vector.