フィルターのクリア

Find minimum difference between matrices.

9 ビュー (過去 30 日間)
Ronald
Ronald 2013 年 6 月 18 日
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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by