Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a matrix ordered

Tags:

r

I would like to order and trasform the values of a matrix from the biggest to the smallest value as in this simple and replicable example :

 #From :
 d<- c(-2,-34,25,0,13,0,25,-2,1)
 m<- matrix(d,3,3)
 m
     [,1] [,2] [,3]
[1,]   -2    0   25
[2,]  -34   13   -2
[3,]   25    0    1

# To:
m1
     [,1] [,2] [,3]
[1,]    5    4    1
[2,]    6    2    5
[3,]    1    4    3

#25: biggest number therefore -->(1)
#13: second biggest one ---> (2)
# ecc ...
#-34: the smallest one ---> (6)

Any help? Thanks

like image 845
Albert Avatar asked May 05 '16 17:05

Albert


People also ask

What does order matrix means?

The order of the matrix is defined as the number of rows and columns. The entries are the numbers in the matrix and each number is known as an element. The plural of the matrix is matrices.

How do you find the product of a matrix in order?

Matrix Multiplication The number of columns in the first matrix must be equal to the number of rows in the second matrix. That is, the inner dimensions must be the same. The order of the product is the number of rows in the first matrix by the number of columns in the second matrix.

How do you find the rank and order of a matrix?

The rank of a unit matrix of order m is m. If A matrix is of order m×n, then ρ(A ) ≤ min{m, n } = minimum of m, n. If A is of order n×n and |A| ≠ 0, then the rank of A = n. If A is of order n×n and |A| = 0, then the rank of A will be less than n.

Why does matrix order matter?

At the level of arithmetic, the order matters because matrix multiplication involves combining the rows of the first matrix with the columns of the second. If you swap the two matrices, you're swapping which one contributes rows and which one contributes columns to the result.


1 Answers

You can convert d to factor and then get rid of the levels. (This means you don't need any extra packages.)

m1 <- m
m1[]<-unclass(factor(d, levels = sort(unique(d), decreasing=TRUE)))
# alternative solutions from comments
# or levels=sort(-d), thanks, akrun
# or, to make it shorter: m1[] <- unclass(factor(-d))
# or, [eddi's suggestion using implicit conversions]: m1[] <- factor(-m) 
m1
#      [,1] [,2] [,3]
# [1,]    5    4    1
# [2,]    6    2    5
# [3,]    1    4    3
like image 128
lebatsnok Avatar answered Nov 21 '22 15:11

lebatsnok