Distance between elements of two matrices

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!

 Respuesta aceptada

Matt Tearle
Matt Tearle el 13 de Oct. de 2011
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

3 comentarios

Sean de Wolski
Sean de Wolski el 13 de Oct. de 2011
As long as there is at least one zero and at least one one:
[junk idxA] = min(A,[],2);
[junk idxB] = min(B,[],2);
abs(idxA-idxB).'
Maybe?
Matt Tearle
Matt Tearle el 13 de Oct. de 2011
Yeah, the problem statement seemed to imply that the structure was fairly well guaranteed.
Greg Heath
Greg Heath el 14 de Oct. de 2011
Since the original post seems to allow negative values, use
min(abs(A),[],2) etc.
Hope this helps
Greg

Iniciar sesión para comentar.

Más respuestas (1)

Arnaud Joye
Arnaud Joye el 14 de Oct. de 2011

0 votos

Brilliant! Thanks a lot guys, the two codes are working beautifully and it is exactly what I am after! You saved me precious time since I was struggling quite hard on this issue.
Thanks again!

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by