Find minimum difference between matrices.
조회 수: 5 (최근 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.
댓글 수: 0
답변 (2개)
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))
댓글 수: 0
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).
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!