Ismembertol command calculating average between two matched rows

Hi everyone! I have a doubt about the ismembertol command, I'm trying to compare two matrices using this command.
A = [2.5 4.4 ; 3.6 8.9];
B = [2.8 4.6 3 ; 4.9 7.1 5 ; 3.5 8.7 2 ; 3.4 8.8 6 ; 4.9 12.5 4];
[ia,ib] = ismembertol(A,B(:,1:2), 0.2, 'ByRows',true);
a = [A(ia,:) B(ia,3)]
I'd like to obtain 3.6 8.9 4 as a result (4 is the average between the third column of the of the third and fourth rows of B) because there are two rows that match, but it returns:
a =
2.5000 4.4000 3.0000
3.6000 8.9000 5.0000
Thank you!

 Accepted Answer

Note: you made a mistake in your example, it should be:
a = [A(ia, :), B(ib, 3)] %ib to index into b, not ia.
To get the average of all the matches you need to ask ismembertol to return all these matches with 'OutputAllIndices', true. It is then up to you to calculate that average. This would do:
[ia, ib] = ismembertol(A, B(:, 1:2), 0.2, 'ByRows', true, 'OutputAllIndices', true);
a = [A(ia, :), cellfun(@(idx) mean(B(idx, 3)), ib)]
edit: Note that the above (and your original code) will error if a row of A is not found in B. To avoid that:
a = [A(ia, :), cellfun(@(idx) mean(B(idx, 3)), ib(ia))]
edit_edit: And I suspect that your tolerance is not what you think it is. With a relative tolerance of 0.2 all rows of B match the 2nd row of A (and 3 rows match the first row). So possibly you wanted:
[ia, ib] = ismembertol(A, B(:, 1:2), 0.3, 'DataScale', 1, 'ByRows', true, 'OutputAllIndices', true);
Use 'DataScale', 1 to make the tolerance absolute.

2 Comments

Thanks for the quick answer!, I have another problem, I'm still getting the first row of A as a result (2.5 4.4) and I don't want it because 2.5 is not in tolerance (0.2) from 2.8. Do you know how to fix it? Thank you so much.
See my edit about tolerance. Your tolerance is relative. Set 'DataScale' to 1 to make it absolute. However, you'll also need to increase it slightly since with 0.2 nothing in A is in range of B (due to floating point approximation, the difference between 3.4 and 3.6 is just a tad over 0.2

Sign in to comment.

More Answers (0)

Asked:

on 30 Jan 2017

Commented:

on 30 Jan 2017

Community Treasure Hunt

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

Start Hunting!