delete repeated rows from array in matlab in matlab

You can use the unique function in Matlab to get an array of unique values and the indices of the original array that correspond to these values. You can then use these indices to create a new array that contains only the unique values. Here's an example:

main.m
A = [1 2 3 3 4 4 4 5];
[unique_values, unique_indices] = unique(A);
unique_array = A(sort(unique_indices));
108 chars
4 lines

The resulting unique_array will be [1 2 3 4 5]. Note that we first used sort to put the values back in their original order, since unique sorts the values in ascending order by default.

Alternatively, you can also remove the repeated rows using the unique function directly by setting the 'rows' option.

main.m
A = [1 2 3; 1 2 3; 4 5 6; 4 5 6; 7 8 9];
[unique_rows, unique_indices, ~] = unique(A, 'rows', 'stable');
unique_matrix = A(sort(unique_indices), :);
149 chars
4 lines

The resulting unique_matrix will be:

main.m
1 2 3
4 5 6
7 8 9
18 chars
4 lines

Again the 'stable' option preserves the relative order of the rows.

related categories

gistlibby LogSnag