本文介绍了是否在空间中找到与另一个数组接近的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想使用功能ismember,但要使用一定范围.例如,对于array2中的每个元素,我想知道array1中的哪些数据点在与array2n距离之内.

I basically want to use the function ismember, but for a range. For example, I want to know what data points in array1 are within n distance to array2, for each element in array2.

我有以下内容:

array1 = [1,2,3,4,5]
array2 = [2,2,3,10,20,40,50]

我想知道array2中的哪些值与array1相距<= 2:

I want to know what values in array2 are <= 2 away from array1:

indices(1,:) (where array1(1) = 1)     = [1 1 1 0 0 0 0]
indices(2,:) (where array1(2) = 2)     = [1 1 1 0 0 0 0]
indices(3,:) (where array1(3) = 3)     = [1 1 1 0 0 0 0]
indices(4,:) (where array1(4) = 4)     = [1 1 1 0 0 0 0]
indices(5,:) (where array1(5) = 5)     = [0 0 1 0 0 0 0]

缺点:

我的array1是496736个元素,我的array2是9268个元素,所以我宁愿不使用循环.

My array1 is 496736 elements, my array2 is 9268 elements, so aI would rather not use a loop.

推荐答案

使用隐式扩展,在MATLAB R2016b中引入,您可以简单地编写:

Using implicit expansion, introduced in MATLAB R2016b, you can simply write:

abs(array1.' - array2) <= 2

ans =
  1  1  1  0  0  0  0
  1  1  1  0  0  0  0
  1  1  1  0  0  0  0
  1  1  1  0  0  0  0
  0  0  1  0  0  0  0

对于早期的MATLAB版本,您可以使用 bsxfun 函数:

For earlier MATLAB versions, you can get this using the bsxfun function:

abs(bsxfun(@minus, array1.', array2)) <= 2

ans =
  1  1  1  0  0  0  0
  1  1  1  0  0  0  0
  1  1  1  0  0  0  0
  1  1  1  0  0  0  0
  0  0  1  0  0  0  0

希望有帮助!

P.S.关于"MATLAB循环缓慢"的神话,请看看.

P.S. On the "MATLAB is slow for loops" myth, please have a look at that blog post for example.

编辑:请阅读 Adriaan的答案有关使用此和/或他的RAM消耗的信息方法!

Please read Adriaan's answer on the RAM consumption using this and/or his approach!

这篇关于是否在空间中找到与另一个数组接近的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 00:42