I need to read an array to see if it has repeated elements (using for loop)

조회 수: 20 (최근 30일)
For example:
Vec = [2,4,4,6];
For this case, element 4 is repeated.
And i want the code do something like this:
iteration # 1
Vec(1) == Vec(2) , Vec(3), Vec(4)
2 == [4,4,6]
iteration # 2
Vec(2) == Vec(3), Vec(4)
4 == [4,6] % In this case theres a repeted number
iteration # 3
Vec(3) == Vec(4)
4 == [6]
I know i need use two for loops (one for read the first element) and the second loop for to compare the elements:
cont =0;
for i=1:length(Vec)-1
for j = length(Vec):1
if Vec(i) == Vec(j+i)
cont = cont+1
end
end
end
Any idea?

답변 (3개)

Voss
Voss 2022년 1월 20일
You can do it with two for loops like that, but note that if an element occurs more than two times, each pair will be counted, e.g., with Vec = [2 4 4 4], you get Vec(2)==Vec(3), Vec(2)==Vec(4), and Vec(3)==Vec(4). If that's not what you want, you'd have to keep track of which values have been counted aready.
Here's your way of counting repeats, and another possible way.
Note that if all you really need to know is whether there are any repeated elements in a vector (and you don't need to count them), you can simply say: has_repeats = numel(Vec) > numel(unique(Vec));
Vec = [2 4 4 6];
count_repeats(Vec)
ans = 1
count_repeats([2 4 4 4])
ans = 3
count_repeats([2 4 4 4 4 4])
ans = 10
count_repeats_another_way(Vec)
ans = 1
count_repeats_another_way([2 4 4 4])
ans = 2
count_repeats_another_way([2 4 4 4 4 4])
ans = 4
function cont = count_repeats(Vec)
cont = 0;
for i = 1:length(Vec)-1
for j = i+1:length(Vec)
if Vec(i) == Vec(j)
cont = cont+1;
end
end
end
end
function cont = count_repeats_another_way(Vec)
cont = numel(Vec)-numel(unique(Vec));
end

Walter Roberson
Walter Roberson 2022년 1월 20일
cont =0;
for i=1:length(Vec)-1
for j = i+1:length(Vec)
if Vec(i) == Vec(j)
cont = cont+1
end
end
end
However...
Suppose you had [2,4,4,6,4,2,4] then what output would you want, what would you want cont to be at the end ?

Image Analyst
Image Analyst 2022년 1월 20일
Why use a for loop??? No need to go to that complication (unless there is something you've not told us.) Why not simply use unique() and length()?
if length(unique(v)) == length(v)
fprintf('No repeated values.\n');
else
fprintf('At least one value is repeated.\n');
end

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by