Swap k elements in an n x1 vector

3 Ansichten (letzte 30 Tage)
Josue Ortega
Josue Ortega am 16 Nov. 2022
Kommentiert: Stephen23 am 16 Nov. 2022
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 Kommentar
Stephen23
Stephen23 am 16 Nov. 2022
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?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Rik
Rik am 16 Nov. 2022
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.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by