0

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.

ventaquil
2,8584 gold badges25 silver badges52 bronze badges
asked Jan 12, 2020 at 12:03
1
  • 2
    You are stating that your python code behaves different, please add your python code to your question. Commented Jan 12, 2020 at 13:04

1 Answer 1

2

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

enter image description here

When I plot xx and np.diff(xx>0.02) in Python+Numpy+Matplotlib I get

enter image description here

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) )

enter image description here

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...

Cris Luengo
61.4k10 gold badges76 silver badges135 bronze badges
answered Jan 12, 2020 at 13:24
Sign up to request clarification or add additional context in comments.

2 Comments

Your explanation about MATLAB is slightly off, xx>0.002 is of data type logical, but the result of false-true is a double of value -1.
@Daniel I'll correct the answer, thank you for the correction.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.