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

9 ビュー (過去 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 件のコメント
Vanessa Huijgevoort
Vanessa Huijgevoort 2021 年 2 月 4 日
Ah thank you that worked!
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by