remove reoccuring numbers in matrix in matlab

One way to remove recurring numbers in a matrix in MATLAB is to use the unique function. We can traverse the matrix using loops and check if the element is unique or not using the unique function. Then, we can store the unique values in a new matrix using logical indexing.

Here's some code that demonstrates this approach:

main.m
% Defining the matrix
A = [1 2 3 4; 5 6 5 7; 8 9 9 10; 11 12 13 14];

% Initializing the new matrix
B = [];

% Traversing the matrix
for i = 1:size(A,1)
    for j = 1:size(A,2)
        
        % Checking if the element is unique
        if sum(A(i,j)==B)==0
            B = [B A(i,j)];
        end
        
    end
end

% Displaying the result
disp(B);
354 chars
21 lines

In this code, we first define the matrix A. Then, we initialize an empty matrix B, which will store the unique values of A.

We then traverse the elements of A using nested loops. For each element, we check if it is unique or not by using the unique function in combination with logical indexing. If the element is unique (i.e., its count is zero in matrix B), we append it to B.

Finally, we display the content of B, which will only contain the unique elements of A.

gistlibby LogSnag