I need to read an array to see if it has repeated elements (using for loop)
    9 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
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?
0 Kommentare
Antworten (3)
  Voss
      
      
 am 20 Jan. 2022
        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)
count_repeats([2 4 4 4])
count_repeats([2 4 4 4 4 4])
count_repeats_another_way(Vec)
count_repeats_another_way([2 4 4 4])
count_repeats_another_way([2 4 4 4 4 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
0 Kommentare
  Walter Roberson
      
      
 am 20 Jan. 2022
        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 ?
0 Kommentare
  Image Analyst
      
      
 am 20 Jan. 2022
        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
0 Kommentare
Siehe auch
Kategorien
				Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!