How to compare some specific entries of a matrix, if I have their indices stored in 2 files?

1 view (last 30 days)
I have 2 files, that have numbers that represent rows and columns respectively, out of which I want to pick a pair at a time, and compare that corresponding element from a given matrix. For example, if I have matrices A and B, such that:-
A= [1,5,9] and B= [2,6,11]
Then I want to compare the (1,2), (5,6) and (9,11) elements of a matrix C, and return the indices of the largest value.
Originally, my matrix A and B are 19007x1 in size. And my matrix C is 5601x5601 in size.

Accepted Answer

José-Luis
José-Luis on 7 Jul 2017
idx = sub2ind(size(C), A, B)
result = max(C(idx));
  7 Comments
Guillaume
Guillaume on 7 Jul 2017
Edited: Guillaume on 7 Jul 2017
The problem is with the find(C == max(C(idx))), you can't use find on the full C matrix, you have to do it on the subset indexed by idx, so:
find(C(idx) == max(C(idx)))
edit, after José-Luis edit while I was writing my comment: while the new code may provide correct results most of the time, this is still wrong. As it searches the whole C matrix, not just the subset provided by A and B. Try with example:
A = 1;
B = 1;
C = [0 0; 0 0];
José-Luis
José-Luis on 7 Jul 2017
Edited: José-Luis on 7 Jul 2017
True, didn't think of that. Yet another edit.
A = [ 1 , 2 , 7 ];
B = [ 5 , 4 , 8];
C = rand(10);
idx = sub2ind(size(C),A,B);
[idx_x, idx_y] = find(C(idx) == max(C(idx)));
x = A(idx_x);
y = B(idx_y);

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 7 Jul 2017
As per José-Luis' answer, you have to use sub2ind to convert your 2D indexing from A and B into linear indices. This would work:
index = sub2ind(size(C), A, B);
[~, row] = max(C(index));
row is the row in A and B where the maximum is found. If there are several locations where it is found, then you only get the first one. If you want all of them:
Csearch = C(sub2ind(size(C), A, B));
rows = find(Csearch == max(Csearch));

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!