Dr. Zezo
Dr. Zezo

Reputation: 415

How to normalize an array between min and max value

I have an array:

list = [[2310.01, 2640.14, 2710.63, 2926, 2700.12],
        [2014.45, 2160, 2430.65, 2700.65, 2714.63]]

I need to normalize each row in a 2D list between (min=-.1, max=.1). All methods can normalize the data between [0,1] or [-1,1]. But, since I have 2D array, I need to normalize each row between some min/max value, for example: (-.1, .1).

I am using Python and MATLAB, hope I can get answers with python or matlab.

Upvotes: 0

Views: 2353

Answers (4)

NCC1701
NCC1701

Reputation: 149

There is a great function in Matlab called "mapminmax" developed for this job.

x=data;
[x_normalized, PS]=mapinmax(x',0,1); % It makes normalization in the range of 0-1.
x_normalized=x_normalized';

The function examines the rows, for these reason we have to do the x 'operation because we want to normalize according to the columns. The PS parameter will represent the parameters required when we want to convert it to the actual value before normalization.

x = (mapminmax('reverse',x_normalized',PS))' % Obtaining the true value of x.

Upvotes: 0

Alex Taylor
Alex Taylor

Reputation: 1412

In R2018a and later, you can use the normalize function directly in MATLAB to do this.

A = magic(3)

A =

 8     1     6
 3     5     7
 4     9     2

normalize(A,2,'range',[-1 1])

ans =

1.0000   -1.0000    0.4286
-1.0000         0    1.0000
-0.4286    1.0000   -1.0000

Upvotes: 0

Rotem
Rotem

Reputation: 32104

In MATLAB, you can do it as following:

Normalize to range [-1, 1]:

norm_list = ((list - min(list, [], 2)) ./ (max(list, [], 2) - min(list, [], 2)))*2 - 1

Not the best, but quickest solution I thought of...


Update - normalizing to general destination range:

lo_out = -0.1
hi_out = 0.1
range_out = hi_out - lo_out

%Normalize to range [0, 1]:
%norm_list = (list - min(list, [], 2)) ./ (max(list, [], 2) - min(list, [], 2))

%Normalize to range [lo_out, hi_out]:
lo_in = min(list, [], 2); %Minimum of each row
hi_in = max(list, [], 2); %Maximum of each row
range_in = hi_in - lo_in; %Range of each row

norm_list = ((list - lo_in) ./ range_in) * range_out + lo_out

Upvotes: 1

Abinav R
Abinav R

Reputation: 375

The simplest way will be to do min-max normalization

np.array(list)
array = list[:] - np.min(list) / (np.max(list) - np.min(list))
array = 2*array - 1

Now the array is normalised between -1 and 1

Upvotes: 0

Related Questions