user3711804
user3711804

Reputation: 3

Trying to compare elements of on array with every element of another array in matlab

I'm using Matlab, and I'm trying to come up with a vectorized solution for comparing the elements of one array to every element of another array. Specifically I want to find the difference and see if this difference is below a certain threshold.

Ex: a = [1 5 10 15] and b=[12 13 14 15], threshold = 6

so the elements in a that would satisfy the threshold would be 10 and 15 since each value comes within 6 of any of the values in b while 1 and 5 do not. Currently I have a for loop going through the elements of a and subtracting an equivalently sized matrix from b (for 5 it would be a = [5 5 5 5]). This obviously takes a long time so I'm trying to find a vectorized solution. Additionally, the current format I have my data in is actually cells where each cell element has size [1 2], and I have been using the cellfun function to perform my subtraction. I'm not sure if this complicates the solution of each [1 2] block with the [1 2] block of the second cell. A vectorized solution response is fine, there is no need to do the threshold analysis. I just added it in for a little more background.

Thanks in advance,

Manwei Chan

Upvotes: 0

Views: 117

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

Use bsxfun:

>> ind = any(abs(bsxfun(@minus,a(:).',b(:)))<threshold)
ind =
     0     0     1     1

>> a(ind)
ans =
    10    15

Upvotes: 1

Related Questions