MATLAB 到 Python 代码转换(NumPy、SciPy、MatplotLib?)

2023-12-02

我正在尝试将以下代码从 MATLAB 转换为 Python 以用于 EEG 项目(部分原因是 Python 稍微便宜一些!)

希望有人能指出我正确的方向:我已经开始改变它但陷入困境:特别是试图找到等效的功能。

尝试过 scipy.org (NumPy_for_Matlab_Users 等),但我不确定我的参数是否具有正确的格式/数字)

我最初使用的是 pyserial

ser.read()

读取数据然后

ord()

将其转换为整数,但此 MATLAB 代码以另一种方式处理('uchar')

我的主要问题是

fopen
fread
find
repmat

整个绘图部分我对 Python 的了解更少(MatPlotLib?)

MATLAB 也倾向于以“1”开头,而 Python 使用 0:我也尝试过更改这些,但遗漏了一些我不确定的内容。

Python 是否满意用冒号分隔的整个范围

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

or not?

所以,这是 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');

这是我可怜的表弟的版本

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

非常感谢所有建议!

Dave!


嗯...很多事情。

Python没有end关键字,所以你显然需要阅读更多有关 Python 语法的内容。

Python 数组和切片的索引为[] not ()。例如,范围表示为 range(0,10),但 Matlab 意义上的切片仅存在于 numpy 等扩展包中,并且每个切片都有自己的接口。

是的,您想使用 matplotlib 进行绘图,它具有与 Matlab 绘图界面几乎相同的功能,至少在这个级别上如此。

看起来您猜测 Python 在某些随机包中将具有与 Matlab 相同的方法名称。这不是一个好计划。相反,请在其在线文档中查找 Matlab 方法,准确了解其用途,然后阅读 Python 包文档,找到可以执行您想要的操作的方法。这可能不存在,但我敢打赌,在这么简单的程序中,您需要的大多数程序都会存在。

在将任何 Matlab 代码转换为其他语言时,您需要了解的最重要的事情是 Matlab 数组的工作方式,这非常不寻常(但对于其目标应用程序来说非常好)。 Numpy 具有大致相同的功能,但它们的表示法完全不同。

串行模块已经在端口上为您提供了一个打开的文件对象,因此您不需要 fopen。

我认为您需要花费大量时间来阅读 Python 和 Matlab 的文档,因为很明显您目前对两者都不了解。

不要让我让你泄气,我只是诚实地告诉你你的处境。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MATLAB 到 Python 代码转换(NumPy、SciPy、MatplotLib?) 的相关文章

随机推荐