Jose Guilherme
Jose Guilherme

Reputation: 355

Plotting RMS from np.vector

I have an array that I need to slice it in many other arrays, calculate rms from the sliced array, and them plot the result of the rms in a graph. I wrote the code bellow, where I could print all the rms values from an array, although I am not being able to "store" this results to plot it. Can anyone help me?

import numpy as np
import matplotlib.pyplot as plt

# Number of samplepoints
N = 10000
# sample spacing
T = 1.0 / 800.0
t = np.linspace(0.0, N*T, N)
y1 = np.sin(50.0 * 2.0*np.pi*t)

plt.figure(1)
plt.plot(t,y1)
plt.show()

i = 0

while (i < len(y1)):
    i1 = i
    i2 = i1+1000
    x = y1[i:i2]
    rms = np.sqrt(np.mean(x**2))
    i = i2
    print (rms)

else:
    print("finish")

Upvotes: 0

Views: 1242

Answers (1)

Mr. T
Mr. T

Reputation: 12410

You could of course create a list l and add each rms value with l.append(rms). But you have already a nice numpy array, so why not use it:

#reshape y1 as 10 columns with 1000 rows 
arr = y1.reshape(10, 1000).T
#square each value, calculate mean for each column (axis 0), then calculate the sqrt for each result
rms = np.sqrt(np.mean(np.square(arr), axis = 0))
print(rms)

Sample output:

[0.70707275 0.70707187 0.70707121 0.70707076 0.70707054 0.70707054
 0.70707076 0.70707121 0.70707187 0.70707275]

which is what you also calculated in your loop. And this you can now plot additionally into your figure, if you move the plotting function to the end of your script.

Upvotes: 1

Related Questions