Shifting position of an element in a vector from 1st to last

10 ビュー (過去 30 日間)
Ayesha Maroof
Ayesha Maroof 2019 年 3 月 14 日
編集済み: Jan 2019 年 3 月 16 日
i want to change the position of a number in element from 1st to last
for example if i have a sequence 1-2-3-4-5
first i want to move 1 to end of vector like 2-3-4-5-1
then i want to move 2 like 1-3-4-5-2
then 3, 1-2-4-5-3
and so on withoutchanging order of other.i can do it with for loop but is there a single command for this in Matlab??
  2 件のコメント
Jan
Jan 2019 年 3 月 14 日
編集済み: Jan 2019 年 3 月 14 日
You want to get different outputs. Then it is not clear, what kind of "single command" you want for this job. It is not clear, what you want as output. But solving this with a for loop is easy, so why don't you use it?
Ayesha Maroof
Ayesha Maroof 2019 年 3 月 14 日
Because i am lookig for a single command.
if 1-2-3-4-5 is the main sequence, i want all combinations like this:
2-3-4-5-1
1-3-4-5-2
1-2-4-5-3
1-2-3-5-4
like this.I want to move step by step elements to end without changing the main sequence

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

採用された回答

Stephen23
Stephen23 2019 年 3 月 14 日
Here is a general solution for any sized vector (not in a single command though):
>> N = 5;
>> V = 1:N
V =
1 2 3 4 5
>> [~,X] = sort(eye(N),2);
>> M = V(X)
M =
2 3 4 5 1
1 3 4 5 2
1 2 4 5 3
1 2 3 5 4
1 2 3 4 5
  2 件のコメント
Ayesha Maroof
Ayesha Maroof 2019 年 3 月 16 日
Thank you soooo much Stephen.anyway its better than using a for loop.
Jan
Jan 2019 年 3 月 16 日
+1. When the vector is 1:N, the single command is working already:
[~,X] = sort(eye(N),2)

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

その他の回答 (1 件)

Jan
Jan 2019 年 3 月 16 日
編集済み: Jan 2019 年 3 月 16 日
Or:
X = [(1:N-1) + triu(ones(N, N-1)), (1:N).']
% Auto-expanding: >= R2016b
This is 2 times faster for N=200, and 3 times for N=400 than sorting the eye matrix, but less nice.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by