0

Let there be two arrays {A,B} of size 1xN

I want to find the number of cases where on the same indices

the condition A(ii)==1 & B(ii)==0 is satisfied.

I tried

casess= intersect( find(A==1),find(B==0 ))

but this is very slow.

I believe this is because intersect checks on every member if it is member of the other group, but I am still looking for the fastest solution to my smaller problem.

JohnnyF
  • 1,053
  • 4
  • 16
  • 31
  • 2
    Try this: `casess = sum(A == 1 & B == 0);` There is no need to use `find` or `intercept` for simple logical computations. – buzjwa Aug 25 '15 at 09:20
  • Ps looking for something nuicer then a for loop – JohnnyF Aug 25 '15 at 09:20
  • Naveh and if i want to get the indices of those cases? – JohnnyF Aug 25 '15 at 09:21
  • 3
    _Then_ you should use `find`: `indices = find(A == 1 & B == 0);`. By the way, you might not even need the indices and can simply use logical indexing, depending on what you want to do with them. For example, if `C` is also of the same size, `vals = C(A == 1 & B == 0);` will give you the values of `C` for the indices you would get with the above `find`. – buzjwa Aug 25 '15 at 09:22

1 Answers1

5

The number of cases where this condition is true can be computed with:

numCases = sum(A == 1 & B == 0);

The expression A == 1 & B == 0 gives a logical array which can be used, for example, to find the indices where the condition is true:

ind = find(A == 1 & B == 0);

or to directly access a matrix with the same size via logical indexing:

C = zeros(size(A));
C(A == 1 & B == 0) = 5;
buzjwa
  • 2,632
  • 2
  • 24
  • 37
  • great ans!. now numCases = sum(A == 1 & B == 0); is the slowest part, any chance to speed it up? even in the cost of mex file or w/e? – JohnnyF Aug 25 '15 at 10:24
  • What is the size of the arrays, and what running times are you seeing? you can try [`nnz`](https://www.mathworks.com/help/matlab/ref/nnz.html) instead of `sum`. I'm not sure which would be faster. – buzjwa Aug 25 '15 at 10:30
  • From a quick check, `sum` and `nnz` show similar speeds. However, here's something interesting: if `A` and `B` are both non-negative, then `sum(A + B - 1 == 0)` is ten times faster than `sum(A == 1 & B == 0)`. I don't know if this is relevant for your data, though. – buzjwa Aug 25 '15 at 10:40
  • 1
    Slight correction: `B` has to be strictly positive for this method to be equivalent to the original one. The point is that arithmetic operations can be faster than logical operations, and this can be utilized to your advantage if some restrictions on the data can be made. – buzjwa Aug 25 '15 at 12:04
  • Glad to have helped :) – buzjwa Aug 25 '15 at 13:21