Sorting all columns in a matrix and sortmc

How can I sort all columns in a matrix without doing a loop? I cannot get the sortmc command to work.

 

 

1 Answer



0



The best way to sort an entire matrix is probably with a loop. You can make a procedure to hide the details to make your code cleaner, like this:

proc (1) = sortallc(x);
   for i(1, cols(x), 1);
      x[.,i] = sortc(x[.,i], 1);
   endfor;
   retp(x);
endp;

Then in your code, you would just need to say:

newx = sortallc(x);

The sortmc command keeps all rows together. Since in many cases, rows are observations this is what is most commonly needed. What it does differently is that it will sort later columns based upon tie breakers in the first specified search column. So, the code:

x = { 9 2 5 6,
      3 6 1 9,
      3 7 4 1,
      1 2 8 9 };
	 
s1 = sortc(x,1);

s2 = sortmc(x, 1|2);

will set 's1' and 's2' equal to:

     1      2      8      9 
s1 = 3      7      4      1 
     3      6      1      9 
     9      2      5      6 

     1      2      8      9 
s2 = 3      6      1      9 
     3      7      4      1 
     9      2      5      6 

Notice that rows 2 and 3 have been swapped in 's2' because the matrix was sorted based upon row 2 for the rows that matched in column 1.

aptech

983

Your Answer

1 Answer

0

The best way to sort an entire matrix is probably with a loop. You can make a procedure to hide the details to make your code cleaner, like this:

proc (1) = sortallc(x);
   for i(1, cols(x), 1);
      x[.,i] = sortc(x[.,i], 1);
   endfor;
   retp(x);
endp;

Then in your code, you would just need to say:

newx = sortallc(x);

The sortmc command keeps all rows together. Since in many cases, rows are observations this is what is most commonly needed. What it does differently is that it will sort later columns based upon tie breakers in the first specified search column. So, the code:

x = { 9 2 5 6,
      3 6 1 9,
      3 7 4 1,
      1 2 8 9 };
	 
s1 = sortc(x,1);

s2 = sortmc(x, 1|2);

will set 's1' and 's2' equal to:

     1      2      8      9 
s1 = 3      7      4      1 
     3      6      1      9 
     9      2      5      6 

     1      2      8      9 
s2 = 3      6      1      9 
     3      7      4      1 
     9      2      5      6 

Notice that rows 2 and 3 have been swapped in 's2' because the matrix was sorted based upon row 2 for the rows that matched in column 1.


You must login to post answers.

Have a Specific Question?

Get a real answer from a real person

Need Support?

Get help from our friendly experts.

REQUEST A FREE QUOTE

Thank you for your interest in the GAUSS family of products.

© Aptech Systems, Inc. All rights reserved.

Privacy Policy | Sitemap