Find minimum difference between matrices.

2 次查看(过去 30 天)
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.

回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-6-18
编辑:Azzi Abdelmalek 2013-6-18
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
Matt Kindig 2013-6-18
编辑:Matt Kindig 2013-6-18
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).

类别

Help CenterFile Exchange 中查找有关 Descriptive Statistics and Visualization 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by