How do you detect duplicate values within a random array?

Write a program to find if a vector of random generated integers contains any duplicate element. Return true if any value appears at least twice in the said vector and return false if every element is distinct.
I simply have no idea how to implement this. I believe this problem requires a for loop and a series of if statements.

 採用された回答

KSSV
KSSV 2020 年 3 月 31 日

2 投票

If you want to use inbuilt functions......you can use unique. Read about it. Let A be your array.
B = unique(A) ;
if length(A)==length(B)
fprintf('No elements repeated')
else
fprintf('Elements repeated')
end

5 件のコメント

Aaron Zambiasi
Aaron Zambiasi 2020 年 3 月 31 日
Thank you so much for the timely response!
Aaron Zambiasi
Aaron Zambiasi 2020 年 3 月 31 日
So it looks like your code says if the lengths of array A and array B are equal, then display 'No elements repeated'. But since B utilizes A to create a unique array, the lengths of A and B will always be equal, so 'No elements repeated' will always be displayed.
I'm looking for a code that (during the use of a random array) detects if there exist any duplicate random integers generated within that array.
KSSV
KSSV 2020 年 3 月 31 日
Read about loops..you can use two fo rloops and comapre the elements to see, if any element is repeating.
Image Analyst
Image Analyst 2020 年 3 月 31 日
Aaron, not true. The lengths are different if there are repeats because unique() throws out the repeats and sorts the values. Just look
A = [1, 2, 3, 4]
B = unique(A)
fprintf('length(A) = %d. length(B) = %d.\n', length(A), length(B));
A = [1, 2, 2, 2, 9, 5]
B = unique(A)
fprintf('length(A) = %d. length(B) = %d.\n', length(A), length(B));
A =
1 2 3 4
B =
1 2 3 4
length(A) = 4. length(B) = 4.
A =
1 2 2 2 9 5
B =
1 2 5 9
length(A) = 6. length(B) = 4.
Aaron Zambiasi
Aaron Zambiasi 2020 年 3 月 31 日
編集済み: Aaron Zambiasi 2020 年 3 月 31 日
Oh! That makes so much more sense. Thank you both so much! I apologize for my lack of understanding originally. I am still super new at this program.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2020 年 3 月 31 日

編集済み:

2020 年 3 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by