Effacer les filtres
Effacer les filtres

Can I use randi and say random number from 1 to 30 except 8 and 9? (for example)

14 vues (au cours des 30 derniers jours)
Hi everyone. I have some bad data that I have to exclude from my random index selecter but I can't remove it from my data.
For example, I wanted to say Random integer from 1 to 30, but exclude 8 and 9
This works but when I try to add another integer, like 8 and 9 for example, it doesn't work.
randRow = randi(30,1);
while randRow == 8
randRow = randi(30,1);
end
Do you guys know the right syntax? or is there an easier way to do it?

Réponse acceptée

Stephen23
Stephen23 le 18 Juin 2021
Modifié(e) : Stephen23 le 18 Juin 2021
This is MATLAB, so your first thought should always be to use arrays and indexing:
vec = setdiff(1:30,8:9) % or [1:7,10:30] or whatever
vec = 1×28
1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
val = vec(randi(numel(vec)))
val = 22
  3 commentaires
Stephen23
Stephen23 le 21 Juin 2021
vec = setdiff(1:30,[8,9,11,15,18])
vec = 1×25
1 2 3 4 5 6 7 10 12 13 14 16 17 19 20 21 22 23 24 25 26 27 28 29 30
How to generate and concatenate vectors is explained here
Akana Juliet
Akana Juliet le 21 Juin 2021
This is perfect, thanks so much!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

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

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by