# Find minimum difference between matrices.

23 views (last 30 days)
Ronald on 18 Jun 2013
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
A=randi(4,4)
B=randi(4,4)% Example
b=B(:);
for k=1:numel(A)
[val,idx]=min(abs(b-A(k)));
C(k)=val;
end
C=reshape(C,size(A))
%If you do not allow repetition
A=randi(4,4)
B=randi(4,4)
b=B(:);
for k=1:numel(A)
[val,idx]=min(abs(b-A(k)));
C(k)=val;
b(idx)=[];
end
C=reshape(C,size(A))

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).