Swap k elements in an n x1 vector

조회 수: 1 (최근 30일)
Josue Ortega
Josue Ortega 2022년 11월 16일
댓글: Stephen23 2022년 11월 16일
Hi I have a vector which is a random permutation of [1:n]. Say
x=randperm(n)
I want to create a vector that is equal to x, but different in at most c positions. For example, if c=2 and
x=[1 2 3 4 5 6]
I want to create a vector that looks like
x=[3 2 1 4 5 6]
Any suggestions?
  댓글 수: 1
Stephen23
Stephen23 2022년 11월 16일
Do you require a strict derangement of the swapped values (i.e. swapped values cannot be randomly returned to the same location) or is it permitted that values might be returned to the same location?

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

답변 (1개)

Rik
Rik 2022년 11월 16일
Create a logical vector with at most c true elements. Then permute the values at those positions and use logical indexing to store them back into the original array.

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by