필터 지우기
필터 지우기

Find distance between to elements of a "circular" vector

조회 수: 4 (최근 30일)
Jérôme
Jérôme 2013년 7월 16일
댓글: Andrea Ramazzina 2017년 10월 13일
Hi folks;
I'm being stuck on something that I feel is not so difficult, but I can't find a proper way to do it.
Let's say I have the following vector : v = [6 7 1 3 9 6 8 10]
And let's say I want to know the distance, i.e. number of cells, between the position of 7 and the position of 10. At first glance, it is 6, since starting from 7, you have to move 6 times to the right to get to 10. However, I want to do as if the vector was "circular", like if both ends were connected. So by going two steps to the left, we could reach 10 from 7. The algorithm I want to write should give me the shortest distance, whether it is going to the left or the right.
Do you people se what I mean? I'm not sure it is clear. Hope you can help me. :)

답변 (2개)

Muthu Annamalai
Muthu Annamalai 2013년 7월 16일
Assuming your list is unique you can get the linear positions of two numbers as,
p1 = find( v == n1 )
p2 = find( v == n2 )
% ensure p2 >= p1 always
if ( p2(1) < p1(1) )
t = p1(1); p1 = p2(1); p2 = p1;
end
% forward dist
dist = p2 - p1 + 1
% rev dist
dist2 = p1 - 1 + length(v) - p2
dist = min(dist,dist2)
  댓글 수: 1
Andrea Ramazzina
Andrea Ramazzina 2017년 10월 13일
t = p1(1); p1 = p2(1); p2 = t;
I think you had a mistake, this should be the right one

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 16일
편집: Azzi Abdelmalek 2013년 7월 16일
v = [6 7 1 3 9 6 8 10]
a1=7;
id1=2
a2=10 % number to find
vi1=[v v]
ii1=find(vi1==a2)-id1
idx1=min(ii1(find(ii1>0)))
vi2=fliplr([v v])
id2=numel(v)-id1+1
ii2=find(vi2==a2)-id2
idx2=min(ii2(find(ii2>0)))
idx=min(idx1,idx2)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by