Instead of using the absolute difference for each dimension separately, compute the Euclidean distance between the rows of A and B. This is done using sqrt(sum((A - B_pair).^2, 2)). And then use min(distances) to find the index of the row in A that is closest to the current row in B.
This should ensure that each row in matrix B gets the identifier of the closest row in matrix A.
Refer to the snippet below:
A(:,1) = stvar(1) + (stvar(end) - stvar(1)) * rand(n,1);
A(:,2) = ndvar(1) + (ndvar(end) - ndvar(1)) * rand(n,1);
iden_A = randi([1, n/2], n, 1);
B(:,1) = stvar(1) + (stvar(end) - stvar(1)) * rand(n,1);
B(:,2) = ndvar(1) + (ndvar(end) - ndvar(1)) * rand(n,1);
distances = sqrt(sum((A - B_pair).^2, 2));
[~, minloc] = min(distances);
iden_B = [iden_B; iden_A(minloc)];
disp(A);
3.7020 0.4212
0.6053 -0.3360
1.0224 0.9213
3.7692 0.6286
2.7539 0.9528
3.5434 -0.5355
2.4248 0.8720
0.8152 -0.8384
1.6536 0.9495
3.6147 -0.7808
disp('Identifiers of Matrix A:');
disp(B);
0.9341 0.0032
0.7069 -0.3004
2.5137 -0.5250
1.8370 0.5525
3.6043 -0.0645
2.3333 0.9780
1.9238 -0.2512
3.7867 -0.5267
2.2506 0.4221
3.3141 -0.4006
disp('Identifiers of Matrix B:');
Let's go through the first few rows of B and verify the calculations:
Row 1 of B: ( [0.9341, 0.0032] )
- Calculate Euclidean distances to each row in A:
distances = sqrt(sum((A - [0.9341, 0.0032]).^2, 2))
= [2.8259, 0.3990, 0.9344, 2.8985, 1.9816, 2.7432, 1.6181, 0.8511, 1.0655, 2.8735]
- The minimum distance is 0.3990, which corresponds to row 2 in A.
- Identifier for row 2 in A is 2.
- So, iden_B(1) = 2.
Row 2 of B: ( [0.7069, -0.3004] )
- Calculate Euclidean distances to each row in A:
distances = sqrt(sum((A - [0.7069, -0.3004]).^2, 2))
= [3.0764, 0.1033, 1.2538, 3.1488, 2.2337, 2.8363, 1.9807, 0.5451, 1.3885, 2.9975]
- The minimum distance is 0.1033, which corresponds to row 2 in A.
- Identifier for row 2 in A is 2.
- So, iden_B(2) = 2.