i have matrix C9x9 from real numbers. i need to make program in matlab which checking duplicates above main diagonal,if there're i must print first duplicate value that is found and searching break, if there're not i must print message 'no duplicates'.
i have some code, but this code compare elements above main diagonal with elements under main diagonal. How comparing elements above main diagonal with in range above main diagonal or with in range all matrix?
Code:
A = [1 3 2; 4 5 1; 3 1 1]
A_unique = unique(tril(A, -1));
FLAG = false;
for ii = 1:length(A(1,:))
for jj = ii+1:length(A(1,:))
if (length(A_unique) == length(unique([A_unique; A(ii,jj)])))
display(A(ii,jj))
FLAG = true;
break;
end
end
if ~FLAG
display('no duplicates')
end
end
To explain the first code that you have posted I have added comments:
Code:
A = [1 3 2; 4 5 1; 3 1 1]
A_unique = unique(tril(A, -1)); %tril(A,-1) generates an intermediate array I which has the same elements as A below the
%main diagonal but the other elements are made zero
%The unique function takes I and removes the duplicates present in it giving a column matrix
%A_unique consisting of unique elements of I
FLAG = false;
for ii = 1:length(A(1,:)) %the loops are made to run in the upper half of the array i.e. for all elements in A above the main diagonal
for jj = ii+1:length(A(1,:))
if (length(A_unique) == length(unique([A_unique; A(ii,jj)])))
%if the current element A(ii,jj) is added to the array A_unique and we apply unique function to it,
%the length of the new array will be same as A_unique if A(ii,jj) is already present in A_unique
display(A(ii,jj))
FLAG = true;
break;
end
end
if ~FLAG
display('no duplicates')
end
end
This code has some flaws, for example, the code does not take into account the fact that there is an unwanted 0 added to A_unique always which might be a problem if we declare A as:
A = [1 0 2; 4 5 1; 3 1 1]
Although the element 0 is not present in the elements below the main diagonal, it will be shown to be present in the lower array, all because of the tril function used.
To extract only the upper triangular numbers into a column vector, you could use:
Code:
Aupper = A(triu(ones(size(A)))==1);
I think it is easier to find all duplicates than just the 'first' one. (How do we even define "first"?). However, assuming we want to progress through A column-wise, we could use:
Code:
B = unique(Aupper,'stable');
first_duplicate = Aupper(find(Aupper(1:length(B)) ~= B, 1))
The first line finds unique values in the order they appear. The second line finds the first place where the input vector and the 'uniques' are different (i.e. the first duplicate) and prints out that value.