Creating a Sorting Procedure

The commands and program below allow the easy sorting and analysis of a set of data.

>    with(linalg):

Warning, the protected names norm and trace have been redefined and unprotected
Create a data matrix.

>    A:=matrix(5,3,[a,12,34,b,32,54,c,24,45,d,33,42,e,21,60]);

A := matrix([[a, 12, 34], [b, 32, 54], [c, 24, 45], [d, 33, 42], [e, 21, 60]])

Below we create a program for sorting the data based on a particular column in ascending order.

>   

sortcol := proc(A,N)

>    local i,j,n;
>    n := rowdim(A);
>    for j from 1 to n-2 do
>    for i from 1 to n-1 do
>    if A[i,N] > A[i+1,N] then
>    A := swaprow(A,i,i+1);
>    fi:
>    od: od:
>    evalm(A);
>    end:

Use the routine for sorting columns 2 and 3.

>    sortcol(A,2);

matrix([[a, 12, 34], [e, 21, 60], [c, 24, 45], [b, 32, 54], [d, 33, 42]])

>    sortcol(A,3);

matrix([[a, 12, 34], [d, 33, 42], [c, 24, 45], [b, 32, 54], [e, 21, 60]])

Compute the average of the second column.

>    with(stats):

>    A2 := col(A,2);

A2 := vector([12, 33, 24, 32, 21])

>    A2 := convert(A2,list);

A2 := [12, 33, 24, 32, 21]

>    describe[mean](A2); evalf(%);

122/5

24.40000000

>