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

9 views (last 30 days)
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 Comments
dpb
dpb on 4 Feb 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

Sign in to comment.

Answers (1)

dpb
dpb on 4 Feb 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!