Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize rows of a matrix within range 0 and 1

Tags:

I am trying to normalize all rows of my matrix data at once within range 0 and 1. But I don't know how to do it.. For example, I want to normalize each "obs1", "obs2", "obs3". Thus, minimum, maximum, and sum of each "obs1", "obs2", "obs3" will be used. My data format is,

`mydata

             a        b        c         d         e
obs1   8.15609  11.5379  11.1401   8.95186   7.95722
obs2 339.89800 856.3470 691.3490 590.28600 543.67200
obs3   2.12776  46.4561 136.8860 118.09100 119.86400

`

Also, When I searched to perform this, people used "function()". When/for what does this used?

Thank you very much for your help in advance! :)

like image 619
user2928318 Avatar asked Nov 18 '13 11:11

user2928318


People also ask

How do you normalize data in a matrix?

Normalize data in a vector and matrix by computing the z-score. Create a vector v and compute the z-score, normalizing the data to have mean 0 and standard deviation 1. Create a matrix B and compute the z-score for each column. Then, normalize each row.

How do you normalize a row of a matrix in Matlab?

normalized_M = normr( M ) takes a single matrix or cell array of matrices, M , and returns the matrices with rows normalized to a length of one.


1 Answers

To normalize for each row, you can use apply and then subtract the minimum from each column and divide by the difference between maximum and minimum:

t(apply(mydata, 1, function(x)(x-min(x))/(max(x)-min(x))))

gives you

              a         b         c         d         e
obs1 0.05553973 1.0000000 0.8889038 0.2777796 0.0000000
obs2 0.00000000 1.0000000 0.6805144 0.4848262 0.3945675
obs3 0.00000000 0.3289472 1.0000000 0.8605280 0.8736849

What happens is that you apply the function

function(x){
   (x-min(x))/(max(x)-min(x))
}

to each row of your data frame.

like image 97
user1981275 Avatar answered Oct 06 '22 10:10

user1981275