MATLAB: Sort matrix based on unique values in one column

unique sorting

Hi guys. I can't seem to overcome my problem. I have a matrix with 5 columns and a lot of rows. I need to sort the whole matrix based on unique values in column 1. How do I do that? So I need to find the unique values (its a timestamp from my experiment) in column one and also the corresponding values in the rest of the columns and everything else needs to be deleted. Thanks!

Best Answer

[~,idx] = sort(mat(:,1)); % sort just the first column
sortedmat = mat(idx,:); % sort the whole matrix using the sort indices
You can even do the same thing with unique to get the rows corresponding to unique values in the first column:
[~,idu] = unique(mat(:,1))
uniquerows = mat(idu,:);
Note that unique has options for controlling the order of its outputs, and whether it takes the first or last matching element. You should check its documentation and pick the best options for you requirements.