Swap 3 random elements in an array

How do I randomly swap three elements in an array? The element at selected position one will be moved to selected position two, the previous element at selected position two will be moved to position three, and the element at position three will be moved to selected position one.
For example: a=[4 2 3 1 5 7 6] would become anew=[4 2 6 1 3 7 5]
Thank you

 採用された回答

Steven Lord
Steven Lord 2018 年 8 月 20 日

2 投票

Use randperm to select 3 elements (without replacement) from your vector.
a = [4 2 3 1 5 7 6]
ind = randperm(numel(a), 3)
a(ind) = a(ind([3 1 2]))

1 件のコメント

Amine Ne
Amine Ne 2018 年 8 月 20 日
Thank you Steven Lord, it works well

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

その他の回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2018 年 8 月 20 日
編集済み: KALYAN ACHARJYA 2018 年 8 月 20 日

1 投票

% I have tried this only swap two elements or even numbers, definite swap with each other is only possible in even numbers.
a=randperm(7)
idx=randperm(3);
a(idx)=a(fliplr(idx))
I have tried in another way, you can do that
a=randperm(7)
n=randi(5);
new_array=a(:,:);
new_array([n n+1 n+2])=a([n+2 n n+1])

4 件のコメント

Amine Ne
Amine Ne 2018 年 8 月 20 日
Thank you KALYAN, It does not work for example a = [6 7 1 5 2 3 4] becomes [6 7 1 4 2 7 4].
KALYAN ACHARJYA
KALYAN ACHARJYA 2018 年 8 月 20 日
Wait I am doing, there is little an issue.
KALYAN ACHARJYA
KALYAN ACHARJYA 2018 年 8 月 20 日
I have added (Edited answer) another way, pls try, if OK pls confirm it
Amine Ne
Amine Ne 2018 年 8 月 20 日
編集済み: Amine Ne 2018 年 8 月 20 日
The second solution allows to swap between 3 consecutive elements.
For example: a=randperm(7)=[7 5 4 1 2 3 6];
n=randi(5)=4; new_array=a(:,:);
new_array([n n+1 n+2])=a([n+2 n n+1])=[7 5 4 3 1 2 6]
I think it is good for me, Thank you KALYAN ACHARJYA for your help and your time.

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

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

質問済み:

2018 年 8 月 20 日

コメント済み:

2018 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by