0

Consider three row vectors in Matlab, A, B, C, each with size 1xJ. I want to construct a matrix D of size Kx2 listing every possible pairs of elements (a,b) such that:

  • a is an element of A.

  • b is an element of B.

  • a-b is an element of C.

  • a and b are different from Inf, -Inf.

For example,

A=[-3 3 0 Inf -Inf];
B=[-2 2 0 Inf -Inf];
C=[Inf -Inf -1 1 0];
D=[-3 -2;  %-3-(-2)=-1
    3 2;   % 3-2=1
    0 0];  % 0-0=0

I would like this code to be efficient, because in my real example I have to repeat it many times.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
TEX
  • 2,249
  • 20
  • 43

1 Answers1

1

If J is not too large so that you can afford two intermediate matrices of size up to J×J, this can be done in a vectorized way, which usually means it will be fast:

A = [-3 3 0 Inf -Inf];
B = [-2 2 0 Inf -Inf];
C = [Inf -Inf -1 1 0];
[a, b] = ndgrid(A(~isinf(A)), B(~isinf(B)));
ind = ismember(a-b, C);
result = [a(ind) b(ind)];

This works by generating all pairs that fulfil the individual conditions (such as being finite), and then selecting those pairs that fulfil the joint condition (such as their difference being in a prescribed set of values).

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • could you help me with this related question https://stackoverflow.com/questions/69481450/extracting-positions-of-elements-from-two-matlab-vectors-satisfying-some-criteri?noredirect=1#comment122810124_69481450 – TEX Oct 07 '21 at 13:32
  • 1
    @TEX It looks like you already got a solution :-) – Luis Mendo Oct 07 '21 at 14:24