Generating non-repeating numbers by using a for-loop and break statement

9 vues (au cours des 30 derniers jours)
Vanessa Huijgevoort
Vanessa Huijgevoort le 4 Fév 2021
Réponse apportée : dpb le 4 Fév 2021
Dear all,
I need to make a function that generates a vector x of n random but unique elements that are smaller or equal to m. If a number is repeated, the function should return an empty vector. If not, the function should just return x. I tried using a for-loop and break statement, but they aren't really working properly. This is my code:
function random=r(m,n)
x=randi(m,1,n);
for i=1:m
if sum(x==i)>1
break
disp('[]');
else
disp(x);
end
end
end
Could someone tell me what I'm doing wrong?
Thanks in advance!
Vanessa
  3 commentaires
Vanessa Huijgevoort
Vanessa Huijgevoort le 4 Fév 2021
Ah thank you that worked!
dpb
dpb le 4 Fév 2021
Above answers why the function doesn't display the empty return case; you could remove the need for a loop entirely
function random=r(m,n)
x=randi(m,1,n);
if numel(unique(x)<m)
disp('[]');
else
disp(x);
end
end

Connectez-vous pour commenter.

Réponses (1)

dpb
dpb le 4 Fév 2021
The function doesn't return anything, though...either your original nor mine. I didn't catch that before. If the idea is to return the generated vector if it is unique or an empty vector [] if there is a duplication, then need
function x=r(m,n)
x=randi(m,1,n);
if numel(unique(x)<m)
x=[];
end
end
Above I've also presumed it really is intended to just echo the result to the command line but to return the requested data instead.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by