Post Reply 
Sorting a matrix?
06-18-2015, 01:48 PM
Post: #1
Sorting a matrix?
Looking for ideas:

I need to row sort M1, an (n x 4) matrix, in decreasing order of column 4. Then on decreasing order of column 2, if sorted M1 contains more than one row with equal column 4 values.

How can this be done?

Thanks,

-Dale-
Find all posts by this user
Quote this message in a reply
06-18-2015, 03:26 PM
Post: #2
RE: Sorting a matrix?
This is bulky, but seems to work (better ideas?):

Code:

EXPORT sm(N)
BEGIN
  
  M1:=CAS("randMat(N,3,ip(1..10))");     //  Generate random M1(N,3) cut list: M1[#pieces,length,width] of N patterns 

  for I from 1 to length(M1) do          
    M1(I,4):=M1(I,2)*M1(I,3);            //  Create column 4, M1[#pieces,length,width,area]   
  end;

  for I from 1 to length(M1) do
    for J from I+1 to length(M1) do
      IF M1(I,4)<M1(J,4) then SWAPROW(M1,J,I); end;  //  Sort column 4 in decreasing order
    end;  // J
  end;  // I

  for I from 1 to length(M1)-1 do
    for J from I+1 to length(M1) do
      IF (M1(I,4)==M1(J,4)) AND (M1(I,2)<M1(J,2)) then SWAPROW(M1,I,J); end;  // Then sort column 2 decreasing, if equal col 4 values
    end; // j
  end;  // I
  
END;

tnx,

-Dale-
Find all posts by this user
Quote this message in a reply
06-19-2015, 04:54 AM
Post: #3
RE: Sorting a matrix?
Create a sort function, something like
f:=(x,y)->if y[4]!=x[4] then return x[4]>y[4] else return x[2]>y[2] end;
then sort(m,f) will sort a matrix m using f as a sort function.
Find all posts by this user
Quote this message in a reply
06-19-2015, 10:28 AM
Post: #4
RE: Sorting a matrix?
Thank you for your very helpful suggestion! I like compact solutions like this, and I'll add it to my "how to" list for future reference.

-Dale-
Find all posts by this user
Quote this message in a reply
Post Reply 




User(s) browsing this thread: 1 Guest(s)