Effacer les filtres
Effacer les filtres

How to assign a given value to an element of an array without repeating it.

1 vue (au cours des 30 derniers jours)
Yro
Yro le 27 Mai 2021
Commenté : Yro le 27 Mai 2021
Hello, I need to change the value of an element of the array x for a random value but that this is not repeated in the array. With the following code I check that it is not repeated and then I assign it to the y position.
x = [1 3 5 7 9];
y = randi([1 10]);
n = randi([1 length(x)]);
if ~ismember(y, x)
disp(' NO')
x(n) = y;
else
But the problem is in the case that it is repeated, how could I re-generate another number and perform the previous procedure.
Thanks in advance.

Réponse acceptée

Walter Roberson
Walter Roberson le 27 Mai 2021
x = [1 3 5 7 9]
x = 1×5
1 3 5 7 9
y = setdiff(randi([1 10]), x)
y = 10
n = randi([1 length(x)])
n = 3
ny = randi([1 length(y)])
ny = 1
x(n) = y(ny)
x = 1×5
1 3 10 7 9
  3 commentaires
Walter Roberson
Walter Roberson le 27 Mai 2021
Correction to the code:
x = [1 3 5 7 9]
y = setdiff(1:10, x)
n = randi([1 length(x)])
ny = randi([1 length(y)])
x(n) = y(ny)
So y selects the elements of 1:10 that are not in x, and then ny selects a random member of that, so y can never be something that is already in x. No loop is needed.
Yro
Yro le 27 Mai 2021
Thank you very much for your help, the code works.
Best regards.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by