finding the distance between elements of a vector
Afficher commentaires plus anciens
I have lots of data looking something like this, but actually much larger:
[0 0 0 3 0 0 2 0 -3 0 5 0 -2 0 0 3 0 0 0 0 2 0 -5]
Now I want to be able to extract the index distance between any 2 numbers in the data.
For example say i want to know the distance between 3 and 2, it should give 3 and 5 as result. I'm not too good at Matlab and am not sure if this is possible and how it could be done.
Can anybody help?
2 commentaires
Pawel Blaszczyk
le 30 Sep 2011
Can you explain more clearly?
Why the distance between 3 and 2 is 3 and 5?
The distance is a scalar, not a vector, isn't it?
Jan
le 30 Sep 2011
This is not enough information to create a complete answer. What is the full output for [3, 2, 2], or for [0, 1, 2, 0]?
Réponse acceptée
Plus de réponses (3)
Aurelien Queffurust
le 30 Sep 2011
A=[0 0 0 3 0 0 2 0 -3 0 5 0 -2 0 0 3 0 0 0 0 2 0 -5];
result = [find(A==2)- find(A==3)]
will return :
result =
3 5
Matt Tearle
le 30 Sep 2011
Do you know that you'll always have pairs? That is, could you ever have a vector [0 2 0 -3 0 5 0 -2 0 0 3 0 0 0 0 2 0 -5] or [2 0 3 2 0 -3 0 5 0 -2 0 0 3 0 0 0 0 2 0 -5]? If so, Aurelien's solution will fail. This, sick and wrong though it may be, should work:
A = [0 0 0 3 0 0 2 0 -3 0 5 0 -2 0 0 3 0 0 0 0 2 0 -5];
xyspace = @(v,x,y) cellfun(@length,regexprep(regexp([' ',num2str(v),' '],[' ',num2str(x),' .*? ',num2str(y),' '],'match'),'\W',''))-1;
xyspace(A,3,2)
Note: use Aurelien's solution if you know the numbers will come in pairs!
1 commentaire
Bauke
le 3 Oct 2011
Bauke
le 1 Oct 2011
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!