finding the distance between elements of a vector
57 次查看(过去 30 天)
显示 更早的评论
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 个评论
Pawel Blaszczyk
2011-9-30
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
2011-9-30
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]?
采纳的回答
Matt Tearle
2011-10-3
OK, from what I can tell from your further input, I think this function does what you want.
function d = xyspace(A,x,y)
idx1 = find(ismember(A,x));
idx2 = find(ismember(A,y));
x = union(idx1,idx2);
whichset = ismember(x,idx1) + 2*ismember(x,idx2);
idx = diff(whichset)>0;
d = x([false,idx]) - x([idx,false]);
So now
A = [0 -2 -2 3 0 0 0 -2 -3 0 0 3 0 2 -3 -2 0 3 0 0 2 0 -3 0 -2 0 0 3 2 -3 -2 0 0 3 0];
xyspace(A,3,2)
ans =
2 3 1
I'm not sure what output you expect for the example
A = [2 0 0 3 0 -2 2 0 -3 0 5 3 0 -2 -5 0 0 0 0 0 0 2 0 5 0 3 0 5 0]
My function can do:
xyspace(A,3,[2,5])
ans =
3 10 2
and it gives the distance from any 3 to a following 2 or 5 (whichever comes first). Not sure if that's what you want. If you want both 3-2 and 3-5 distances, you can always just call twice.
2 个评论
Matt Tearle
2011-10-5
Great. If you don't need "x" and "y" to be vectors, you can replace the "ismember(A,x)" (or y) with "A == x" (y).
更多回答(3 个)
Aurelien Queffurust
2011-9-30
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
0 个评论
Matt Tearle
2011-9-30
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!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!