Find minimum difference between matrices.
23 views (last 30 days)
Show older comments
I have two matrices. For each element in the first matrix, I want to find the closest value in the second matrix, and then take the difference, which will be recorded in a third matrix. Any thoughts on the best way to do this? Thank you.
Azzi Abdelmalek on 18 Jun 2013
Edited: Azzi Abdelmalek on 18 Jun 2013
%If you do not allow repetition
Matt Kindig on 18 Jun 2013
Edited: Matt Kindig on 18 Jun 2013
Another way using histc() function (may be faster for large matrices).
A = rand(5,5); %first matrix
B = rand(2,3); %second matrix
B = sort(B(:)); %make B vector and sort for binning convenience
edges = B(1:(end-1)) + 0.5*diff(B); %"edges" are halfway between each B span
edges= [-inf; edges; inf]; %add +/- inf at ends to include all values
[~,whichBin] = histc(A, edges); %get which bin contains each A
% for each value in A, the value in B which is closest to A
%will fall between bin edges k and k+1 (i.e., k-th element of B)
%third matrix is difference between A and the B for that bin
DiffAB = A - B(whichBin);
EDIT: changed to allow A and B to be matrices as well (consistent with Azzi's solution).
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!