Permutation of only x elements of a vector

1 visualización (últimos 30 días)
Josué Ortega
Josué Ortega el 14 de Sept. de 2017
Comentada: Josué Ortega el 14 de Sept. de 2017
Imagine a vector of natural numbers between 1 and 20, say
x=randperm(20)
I want to generate a vector identical to x, but changing the position of exactly 4 elements. How can I do this in general for a vector of m elements, when I want to change n elements?
  2 comentarios
Stephen23
Stephen23 el 14 de Sept. de 2017
"...changing the position of exactly 4 elements"
Do the positions have to change, or do you accept the possibility of the positions (randomly) being the same?
Josué Ortega
Josué Ortega el 14 de Sept. de 2017
I accept that they can remain the same.

Iniciar sesión para comentar.

Respuesta aceptada

Guillaume
Guillaume el 14 de Sept. de 2017
Doesn't your question just reduce to selecting 4 random integers from 1 to numel(x) using either randperm if the elements have to swap or randi if you accept the positions being the same (as per Stephen's question). You can then swap them in a fixed order or using randperm (which runs the risk of not doing any swapping)
x = 1:20;
swapidx = randperm(numel(x), 4); %or randi(n, 1, 4);
x(swapidx) = x(fliplr(swapidx)) %swap 1st index with fourth, 2nd with 3rd
x(swapidx) = x(swapidx(randperm(4))) %swap randomly (may not swap)

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by