MATLAB: Distance between elements of two matrices

coordinate distanceMATLAB

Hi everybody,
I am a new MATLAB user and I have a question about how to compute a distance measure between different elements of two matrices. Let me be clearer and expose my problem as follows:
I have two matrices, X and Y, which dimensions are the same, say m-by-n (2 dimensions). X and Y contains both just 1 zero-element per row and the other elements are non-zero (it could be anything but zeros); the zero-element can be anywhere within each row and is not necessarily "located" in the same cell in X and Y. I would like to compare the "location" of each zero-element by row between X and Y, and then compute how distant they are between each-other. I actually want to know how many cells are there in-between each zero-element. Hence, I would like the distance between coordinates (in each row) and not some measure of distance between the actual value of the different elements.
I hope my post is clear enough! Thanks a lot for any help!

Best Answer

I think this is what you're after. It's a bit brute-force, but I can't think of a neater, vectorized way.
% Make some matrices
n = 4;
M = magic(n);
A = 1-bsxfun(@eq,M,max(M,[],2))
B = ones(n);
B(n:n-1:end-1) = 0
% Actual code:
f = @(k) abs(find(A(k,:)==0,1,'first')-find(B(k,:)==0,1,'first'));
arrayfun(f,1:size(A,1))
If you don't like arrayfun, feel free to replace it with a for-loop (which is all I'm really doing):
d = zeros(size(A,1),1);
for k = 1:size(A,1)
d(k) = abs(find(A(k,:)==0,1,'first')-find(B(k,:)==0,1,'first'));
end