swap only 2 elements in an array

조회 수: 38 (최근 30일)
Erik Lee
Erik Lee 2015년 10월 13일
답변: Mohammed 2023년 5월 27일
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일
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일
Thank you!
Star Strider
Star Strider 2015년 10월 13일
My pleasure!

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

추가 답변 (2개)

Guillaume
Guillaume 2015년 10월 13일
a = randperm(20)
swapidx = randperm(numel(a), 2);
a(swapidx) = a(fliplr(swapidx))

Mohammed
Mohammed 2023년 5월 27일
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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by