normalizing matrix in matlab

Sanich picture Sanich · Nov 13, 2011 · Viewed 12.3k times · Source

I have an rgb image matrix (height*width*3) represented in doubles. After some manipulations on the matrix, some values went biger then 1 or smaller then 0. I need to normalize those valuse back to 1 and 0. Thanks.

Answer

Marek Kurdej picture Marek Kurdej · Nov 13, 2011

Well, just use the indexing by condition. Let's say your matrix is called M. If you just want to set values bigger than 1 to 1 and smaller than 0 to zero, use:

M(M > 1) = 1;
M(M < 0) = 0;

However, if you want to proportionally normalize all the values to the interval [0; 1], then you have to do something similar to:

mmin = min(M(:));
mmax = max(M(:));
M = (M-mmin) ./ (mmax-mmin); % first subtract mmin to have [0; (mmax-mmin)], then normalize by highest value

You have to take account of the case when your matrix M is already in the interval [0; 1] and the normalization is not needed.