Generating non-repeating numbers by using a for-loop and break statement
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
dpb
el 4 de Feb. de 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
Respuestas (1)
dpb
el 4 de Feb. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!