フィルターのクリア

How to obtain next/previous node in a tour represented as an array (=permutation of size n)

1 回表示 (過去 30 日間)
I have been struggling to find an efficient solution to my problem. I am working with tours, which basically are permutations of the numbers 1 to n (n is given).
Now I want to code an anonymous function* that would work as follows:
tour = [1 8 9 7 4 5 2 10 6 3];
Next = nextNode(tour,2);
Next2 = nextNode(tour,3);
Prev = prevNode(tour,10);
Prev2 = prevNode(tour,1);
% result should be:
% Next = 10
% Next2 = 1
% Prev = 2
% Prev2 = 3
Any suggestions and solutions are welcome, thank you!
  1 件のコメント
madhan ravi
madhan ravi 2018 年 12 月 19 日
編集済み: madhan ravi 2018 年 12 月 19 日
Birdman why do you keep deleting my answer? You deleted it three times. What's wrong? It's not nice to delete answers.

サインインしてコメントする。

採用された回答

madhan ravi
madhan ravi 2018 年 12 月 19 日
編集済み: madhan ravi 2018 年 12 月 19 日
Note: your prev should be 2 not 6 maybe you made a typo.
tour = [1 8 9 7 4 5 2 10 6 3];
Next = nextNode(tour,2)
Next2 = nextNode(tour,3)
Prev = prevNode(tour,10)
Prev2 = prevNode(tour,1)
function Result = nextNode(tour,n)
idx=find(tour==n);
if idx==numel(tour)
Result = tour(1);
else
Result = tour(idx+1);
end
end
function Result1=prevNode(tour,n)
idx=find(tour==n);
if idx==1
Result1=tour(end);
else
Result1=tour(idx-1);
end
end
Gives:
Next =
10
Next2 =
1
Prev =
2
Prev2 =
3
  2 件のコメント
Berlibur
Berlibur 2018 年 12 月 19 日
Indeed it was a typo. Thanks for helping me out!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by