drop duplicate rows matlab in matlab

To drop the duplicate rows in a matrix or a table in Matlab, we can use the unique() function. The unique function can be used with the 'rows' option for matrices, and with 'stable' and 'rows' options for tables. The code snippets are provided below for matrices and tables.

Drop duplicate rows in a matrix:

main.m
A = [1 2 3; 4 5 6; 1 2 3; 7 8 9];
B = unique(A, 'rows');
57 chars
3 lines

Drop duplicate rows in a table:

main.m
T = table([1; 2; 1; 3], {'M'; 'F'; 'F'; 'M'}, ...
    [38; 43; 38; 24], 'VariableNames', {'ID' 'Gender' 'Age'});
T2 = unique(T, 'stable', 'rows');
147 chars
4 lines

In the above example for tables, 'stable' option is used to retain the order of the input rows, in the final output.

related categories

gistlibby LogSnag