swap only 2 elements in an array

I'm try to come up with a function that can randomly swap 2 elements (and only 2 at a time) from an array of 20 unique numbers.
Say a=randperm(20) a=[4 1 9 13 5 20 19 ....] would become anew=[19 1 9 13 5 20 4 ....]

 採用された回答

Star Strider
Star Strider 2015 年 10 月 13 日

6 投票

This works:
a=[4 1 9 13 5 20 19]
a([1 7]) = a([7 1])
a =
4 1 9 13 5 20 19
a =
19 1 9 13 5 20 4

6 件のコメント

Erik Lee
Erik Lee 2015 年 10 月 13 日
Thanks, but how do I automate this process?
Star Strider
Star Strider 2015 年 10 月 13 日
This is how I would do it:
a=randperm(20)
idx = randi(20, 1, 2)
a(idx) = a(flip(idx))
This prints out everything so you can verify that it works.
Erik Lee
Erik Lee 2015 年 10 月 13 日
Is there a way I can label the new string 'anew' while keeping the original as 'a'? I need to compare both later.
Star Strider
Star Strider 2015 年 10 月 13 日
To keep the original vector, returning the switched one as ‘anew’, insert one additional assignment:
a=randperm(20)
anew = a
idx = randi(20, 1, 2)
anew(idx) = anew(flip(idx))
The new line simply duplicates ‘a’ as ‘anew’ and does the same operation on ‘anew’ as it originally did on ‘a’.
Erik Lee
Erik Lee 2015 年 10 月 13 日
Thank you!
Star Strider
Star Strider 2015 年 10 月 13 日
My pleasure!

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

その他の回答 (2 件)

Guillaume
Guillaume 2015 年 10 月 13 日

0 投票

a = randperm(20)
swapidx = randperm(numel(a), 2);
a(swapidx) = a(fliplr(swapidx))
Mohammed
Mohammed 2023 年 5 月 27 日

0 投票

if the array is 2D ( two dimantion ) you can use this and get it how it work
a=[10 20
30 40 ]
%For swapping number in Array 2D
%[10 is a 1] & [30 is 2] & [20 is a 3] & 40 is a 4
a([2 3])=a([3 2])
OUTPUT:
a =
10 20
30 40
a =
10 30
20 40

タグ

質問済み:

2015 年 10 月 13 日

回答済み:

2023 年 5 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by