You may use bsxfun
like this for a generalized case.
Code
%%// Slightly bigger example than the original one
mat= [
1 2 3 6;
2 3 4 2;
3 4 5 3;]
test = [
2 3 4 8 5 6 7 1;
3 4 5 3 6 7 8 7;
7 8 9 6 4 5 6 3]
[M,N] = size(mat);
[M1,N1] = size(test);
if N1~=2*N %%// Check if the sizes allow for the required op to be performed
error('Operation could not be performed');
end
[min_vals,index] = min(bsxfun(@minus,mat,reshape(test,M,N,2)),[],3)
Output
min_vals =
-4 -4 -4 -2
-4 -4 -4 -5
-4 -4 -4 -3
index =
2 2 2 1
2 2 2 2
1 1 1 1