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

조회 수: 16 (최근 30일)
Vanessa Huijgevoort
Vanessa Huijgevoort 2021년 2월 4일
답변: dpb 2021년 2월 4일
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
dpb
dpb 2021년 2월 4일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

dpb
dpb 2021년 2월 4일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by