How can I sort a 2-D array in MATLAB with respect to one column?

By : Midhat
Source: Stackoverflow.com
Question!

I would like to sort a matrix according to a particular column. There is a sort function, but it sorts all columns independently.

For example, if my matrix data is:

 1     3
 5     7
-1     4

Then the desired output (sorting by the first column) would be:

-1     4
 1     3
 5     7

But the output of sort(data) is:

-1     3
 1     4
 5     7

How can I sort this matrix by the first column?

By : Midhat


Answers

An alternative to sortrows(), which can be applied to broader scenarios.

  1. save the sorting indices of the row/column you want to order by:

    [~,idx]=sort(data(:,1));
    
  2. reorder all the rows/columns according to the previous sorted indices

    data=data(idx,:)
    
By : Alessiox


I think the sortrows function is what you're looking for.

>> sortrows(data,1)

ans =

    -1     4
     1     3
     5     7
By : Kena


I'd recommend calling a stored procedure that checks if there are any dependencies, then deletes if there aren't any. That way, the check for integrity is done.

Of course, you'd probably want a different stored procedure for singleton deletes vs. batch deleting... The batch delete could look for child rows and return back a set of records that were not eligible for a bulk delete (had child rows).

By : Jeff


This video can help you solving your question :)
By: admin