Convert MATLAB to Python (NumPy, SciPy, MatplotLib?)

I am trying to convert the following code in Python from MATLAB for an EEG project (partly because Python is a little cheaper!)

I hope someone can point me in the right direction: I started changing it, but got stuck: in particular, trying to find equivalent functions.

Trial scipy.org (NumPy_for_Matlab_Users, etc.), but I'm not sure if my arguments have the correct format / number)

I originally used pyserial

ser.read() 

To read the data and then

 ord() 

To convert it to an integer, but this MATLAB code goes about it differently ('uchar')

My main problems were with

 fopen fread find repmat 

And the entire plot plot, since I have even less idea about this in Python (MatPlotLib?)

MATLAB also tends to start with '1', whereas Python uses 0: I also tried changing them, but skipped a few that I didn't know about.

Is Python happy with the entire colon-separated range

 ...repmat(0:2:10, ..... 

or not?

So here is MATLAB:

 % EEG data grabber and plotter N = 256; % Required number of sample frames % Read in a block of data from the OpenEEG board hCom = serial('COM1','BaudRate',57600,'timeout',5); fopen(hCom); numBlocks = (ceil(17*N/256) + 1); rawdata = zeros(numBlocks*256,1); for n = 1:numBlocks rawdata((0:255) + n*256) = fread(hCom, 256, 'uchar'); % Read data end fclose(hCom); % Convert raw data into a Matlab matrix % First find the first frame start startIndex = find(rawdata == 165); while(rawdata(startIndex(1) + 1) ~= 90) startIndex = startIndex(2:end); end % Now extract the samples frameStarts = (0:(N-1))'*17 + startIndex(1); indices = 4 + repmat(frameStarts, 1, 6) + repmat(0:2:10, length(frameStarts), 1); eegData = (rawdata(indices)*256 + rawdata(indices + 1)) - 512; % eegData is now a N by 6 matrix, each column is a channel of sampled data % Plot time-series data figure(1) subplot(2,1,1) plot((0:255)/256,eegData(:,1:2)) xlabel('Time [s]'); ylabel('EEG data'); % Calculate FFT and plot spectra subplot(2,1,2) window = 0.5 - 0.5 * cos(2*pi*(0:255)/255); % Von-Hann Window f = abs(fft(repmat(window',1,2) .* eegData(:,1:2))); plot((0:127),f(1:128,:)) xlabel('Frequency [Hz]'); ylabel('EEG FFT'); 

And here is my version of my cousin

 import scipy import serial #Serial Module to read serial port from numpy import ceil,zeros #Ceil module & zeros for blank matrix N = 256 #no of sample frames (256 = 1s) #Reads a block of data from the serial port ser = serial.Serial('COM18',57600,timeout=5) scipy.fopen(ser) #MATLAB CODE: fopen(ser) is this correct???? numBlocks = (ceil(17*N/256) + 1) rawdata = scipy.zeros(numBlocks*256,1) for n = 1:numBlocks rawdata((0:255) + n*256) = numpyio.fread(ser,256,'i') # read each byte as unsigned integer end ser.close() #convert raw data to MATLAB matrix #find start of frame (1st Byte always 165, 2nd always 90) startIndex = find(rawdata == 165); while (rawdata(startIndex(0) + 1) ~=90) #confirms 165,90 sequence startIndex = startIndex(1:end) #uses rest of frame as data end #Extraction of sample values #MATLAB CODE frameStarts = (0: (N-1))'*17 + startIndex(1); #'#how to transpose matrix('): zip()?? indices = 4 + (numpy.tile(frameStarts, 1,6)) + (numpy.tile(0:2:10,length(frameStarts), 1); eegData = (rawdata(indices)*256 + rawdata(indices +1)) - 512 #values are unsigned integers 0-1023 and must subtract 512 for actual value #eeg data now N*6 Matrix each column is a channel of data #MATLAB CODE: plot time series data (MatPlotLib?) figure(1) subplot (2,1,1) plot((0:255)/256,eegData(:,1:2)) xlabel('Time [s]') ylabel('EEG Voltage') #fft subplot(2,1,2) window = 0.5 - 0.5*cos(2*pi*(0:255)/255); f = abs(fft(repmat(window',1,2) .* eegData(:,1:2))) '#repmat=tile()? matrix transposition (')? plot((0:127),f(1:128,:)) xlabel('Freq [Hz]') ylabel('EEG FFT') 

All suggestions are gratefully received!

Dave!

+4
source share
3 answers

Um ... a lot of things.

Python does not have the end keyword, so you obviously need to learn more about Python syntax.

Python arrays and slices are indexed using [] not () . Ranges are expressed, for example, as a range (0.10), but slices in the sense of Matlab exist only in expansion packs such as numpy, and each of them has its own interface.

Yes, you want to use matplotlib for plotting, it has almost the same capabilities as the Matlab plotting interface, at least at this level.

It looks like you are assuming that Python will have the same method names as Matlab in some random package. This is not a good plan. Instead, find the Matlab method in your documentation that is online, find out exactly what it does, and then read in the Python package documentation the method that does what you want. It may not exist, but I'm sure the program is simple, most of them you need.

The most important thing you need to understand when converting any Matlab code to other languages ​​is how Matlab arrays work, which is extremely unusual (but great for target applications). Numpy has the same features, but they have completely different designations.

The serial module has already provided you with an open object on the port, so you don't need fopen.

I think you need to spend a lot of time on the documentation for both Python and Matlab, because it is very clear that you do not understand either one or the other.

Do not let me dissuade you, I am just honest about where you are.

+11
source

One small point - indexing between them is different. If you just copy everything from MATLAB to Python, as you seem to have done, you will be very confused. MATLAB x (1: 5: end) translates to Python x [0 :: 5]. Return to NumPy for MATLAB users and view the Linear Algebra Equivalents section (about half a page). He gives a dictionary on how to go back and forth.

+5
source

This may or may not work, but you can try converting Matlab to Python, for example mat2py . I have never tried them, but it can save some time. Also, this page is about converting Matlab to Numpy, which can help you get to know the differences between the two.

+2
source

Source: https://habr.com/ru/post/1302244/


All Articles