Home > Net >  Vector Normalization in Python
Vector Normalization in Python

Time:08-12

I'm trying to port this MatLab function in Python:

fs = 128;
x = (0:1:999)/fs;
y_orig = sin(2*pi*15*x);

y_noised = y_orig   0.5*randn(1,length(x));
[yseg] = mapstd(y_noised);

I wrote this code (which works, so there are not problems with missing variables or else):

Norm_Y = 0
Y_Normalized = []

for i in range(0, len(YSeg), 1):
    Norm_Y = Norm_Y   (pow(YSeg[i],2))

Norm_Y = sqrt(Norm_Y)

for i in range(0, len(YSeg), 1):
    Y_Normalized.append(YSeg[i] / Norm_Y)
    print("=    %f" %(i, Y_Normalized[i]))

YSeg is Y_Noised (I wrote it in another section of the code). Now I don't expect the values to be same between MatLab code and mine, cause YSeg or Y_Noised are generated by RAND values, so it's ok they are different, but they are TOO MUCH different.

These are the first 10 values in Matlab:

0.145728655284548
1.41918657039301
1.72322238170491
0.684826842884694
0.125379108969931
-0.188899711186140
-1.03820858801652
-0.402591786430960
-0.844782236884026
0.626897216311757

While these are the first 10 numbers in my python code:

0.052015
0.051132
0.041209
0.034144
0.034450
0.003812
0.048629
0.016854
0.024484
0.021435

It's like mine are 100 times lower. So I feel like I've missed a step during normalization. Can you help ?

CodePudding user response:

You can normalize a vector quite easily in python with numpy:

import numpy as np

def normalize_vector(input_vector):
    return input_vector / np.sqrt(np.sum(input_vector**2))

random_vec = np.random.rand(10)
vec_norm = normalize_vector(random_vec)
print(vec_norm)

You can call the provided function with your input vector (YSeg) and check the output. I would expect a similar output as in matlab.

CodePudding user response:

Actually, I wanted to avoid numpy and write the function myself. I mean, normalization is a mathematical operation, so everyone can write it...

  • Related