Reputation: 67
So I can't find simple way of solving following problem: I've got two matrices with same amount of rows:
A = [547 184 929 306;
296 368 776 509;
745 626 487 511;
189 780 436 818;
687 81 447 795]
B = [644 939 208 195 311 980;
379 876 301 226 923 439;
812 550 471 171 430 111;
533 622 230 228 185 258;
351 587 844 436 905 409]
How can I create matrix C (size(C)=size(B)) in which for every element of matrix B found closest element of matrix A from corresponding row. In current case:
C =
547 929 184 184 306 929
368 776 296 296 776 509
745 511 487 487 487 487
436 780 189 189 189 189
447 687 795 447 795 447
For the moment I've only thought of this:
temp = bsxfun(@eq,abs(bsxfun(@minus,repmat(A,1,1,size(B,2)),permute(B,[1,3,2]))),min(abs(bsxfun(@minus,repmat(A,1,1,size(B,2)),permute(B,[1,3,2]))),[],2));
C = permute(sum(temp.*repmat(A,1,1,size(B,2)),2),[1,3,2]);
So is there any easy and more understandable way to solve this task?
Upvotes: 2
Views: 77
Reputation: 45762
You can also do it using nearest neighbour interpolation:
for row = 1:size(A,1)
I = interp1(A(row,:), 1:size(A,2), B(row,:), 'nearest','extrap');
C(row,:)=A(row,I);
end
Upvotes: 1
Reputation: 112769
The three bsxfun
can be reduced to one by using the second output of min
, which gives the position of the minimum (first line of my code). Those positions are then converted to a linear index, which is applied to A
(second line):
[~, jj] = min(abs(bsxfun(@minus, permute(A, [1 3 2]), B)), [], 3);
C = A(sub2ind(size(B), ndgrid(1:size(B,1),1:size(B,2)), jj));
Upvotes: 1