# Sorting numbers randomly in a specified range without changing their positions

4 vues (au cours des 30 derniers jours)
Ayobami Meadows le 25 Nov 2021
Commenté : Ayobami Meadows le 4 Déc 2021
A = [5 8 8 4 0 0 10 10 2 2];
Since A is in the range of 1:10, I want to sort A such that all the repeated numbers are replaced with numbers that hasn't appeared yet within 1 to 10, slotting those numbers in, randomly, without ascending or descending. All their initial positions should be maintained without changing. All zeros will also be replaced with non-zeros in this specified range. Maybe to get a result like below.
Ans = [5 8 1 4 7 3 10 6 9 2];
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

the cyclist le 26 Nov 2021
% Input
A = [5 8 8 4 0 0 10 10 2 2];
% Find the pool of numbers that are available to fill
% (because they don't appear in A, but are in 1:10, in this case)
pool = setdiff(1:numel(A),unique(A));
% Find the locations to place the numbers
% (i.e. repeats and zeros)
loc = (diff([NaN A]) == 0) | (A==0);
% Fill the locations randomly from the pool
A(loc) = pool(randperm(numel(pool)))
A = 1×10
5 8 7 4 1 6 10 9 2 3
##### 12 commentairesAfficher 10 commentaires plus anciensMasquer 10 commentaires plus anciens
the cyclist le 4 Déc 2021
Sol(i,loc) = pool(randperm(numel(pool)));
Ayobami Meadows le 4 Déc 2021

Great!

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

R2020a

### Community Treasure Hunt

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

Start Hunting!

Translated by