Reputation: 1
I tried to convert Matlab code to Python but in this xx = diff(xx>setpoint);
situation I did not get the same result in python.
fs = 50;
t = [0:1/fs:1];
xx = sin(2*pi*300*t)+2*sin(2*pi*600*t);
xx = xx(:)'/max(abs(xx)); %-- normalize xx
Lx = length(xx);
Lz = round(0.01*fs);
setpoint = 0.02;
%xx = filter( ones(1,Lz)/Lz, 1, abs(xx) );
xx = diff(xx>setpoint);
Actually I don't understand what the statement xx = diff(xx>setpoint)
do.
Upvotes: 0
Views: 324
Reputation: 25093
TL;DR Python is different, you can make Python like Matlab, in this case I prefer the approach of Python.
In Python xx>0.002
is an array of Booleans, False
and True
and np.diff
treats the Boolean values as such, in Matlab xx>0.002
is a matrix of logical values as well but diff
converts them to 0
and 1
before taking the differences and this imply that we have more possibilities in Matlab
In [15]: for a, b in ((0,0), (0,1), (1,0), (1,1)): print(np.diff((a,b)))
[0]
[1]
[-1]
[0]
In [16]: f, t = False, True
...: for a, b in ((f,f), (f,t), (t,f), (t,t)): print(np.diff((a,b)))
[False]
[ True]
[ True]
[False]
When I plot xx
and diff(xx>0.02)
in Matlab (oh well, in Octave...) I have
When I plot xx
and np.diff(xx>0.02)
in Python+Numpy+Matplotlib I get
To have exactly the results of Matlab we can convert the boolean array to an array of floats, just multiplying by 1.0
is OK — so this is the plot of xx
and np.diff( 1.0*(xx>0.02) )
If the aim of the OP is to show where the signal is larger than 0.02
I dare say that the native Python (no conversion to floats) is better at that...
Upvotes: 2