MATLAB 计时器对象会有所帮助。例如,请参阅此链接Using MATLAB to process files in real-time after each instance a file is created by a separate program。
可能会担心同时写入(您的其他进程)和读取(MATLAB)到单个文件。您的情况可能更适合管道而不是文件:管道与临时文件,但我将继续使用基于 MATLAB 的解决方案来进行定时文件读取和绘图更新。
我模仿了你的情况并学到了一些东西:
- MATLAB 文件句柄存储当前位置。但是,如果为 file-id 设置了文件结束标志,则在进行后续调用时,MATLAB 将不会查找新数据
fread
。请参阅以下函数中使用fseek
的变通方法。readFile
- 10 毫秒是乐观的。MATLAB 不会遗漏点,但每次更新通常会添加四个或更多数据点,而不仅仅是一个。
- 如果数据源正在使用缓冲文件写入,则 MATLAB 在缓冲区刷新到磁盘之前不会看到新数据。下面的 python 代码用于模拟数据源。该文件已打开以写入而没有缓冲:
fobj = open('test.dat', 'wb', 0)
.
MATLAB代码如下:
function [t] = livePlot(period, filename)
//% inputs : period : update rate in seconds
//% filename : name of the file to get data from
//%
//% outputs: t : the timer object
//% >> stop(t)
//% ends streaming
//%%
close all;
t = timer('StartDelay', 1, 'Period', period, ...
'ExecutionMode', 'fixedRate');
//%% timer object callback functions
t.StopFcn = {@stopFigure};
t.TimerFcn = {@updateFigure};
//%% initialize timer object user data
d = get(t, 'UserData');
d.data = []; % array for the data to plot
axes('Position', [0 0 1 1], 'Visible', 'off');
d.axes_handle = axes('Position', [.2 .1 .7 .8]);
d.line_handle = plot(NaN,NaN);
d.fid = fopen(filename, 'r');
set(t, 'UserData', d);
start(t);
end
function stopFigure(obj, event)
//% close function handle
d = get(obj, 'UserData');
fclose(d.fid);
end
function updateFigure(obj, event)
d = get(obj, 'UserData');
//% read new data from file
tmp = readFile(obj);
//% append to array in user data
d.data = [d.data transpose(tmp)];
//% update the plot
set(gcf, 'CurrentAxes', d.axes_handle);
set(d.line_handle, 'XData', 1:length(d.data), 'YData', d.data);
//% store the timer object user-data
set(obj, 'UserData', d);
end
function [tmp] = readFile(obj)
//% read binary data. file-ID is in the timer user-data
d = get(obj, 'UserData');
tmp = fread(d.fid);
fprintf('Current file location : %d \n', ftell(d.fid));
//% fprintf('End of file indicator : %d \n', feof(d.fid));
//% reset the end-of-file indicator
fseek(d.fid, -1, 0);
fseek(d.fid, 1, 0);
//% fprintf('End of file indicator : %d \n', feof(d.fid));
set(obj, 'UserData', d);
end
每隔约 10 毫秒将数据写入文件的 Python 代码:
#!/anaconda/bin/python
import numpy as np
from time import sleep
sleep_time = 0.01
sigma = 5
fobj = open('test.dat', 'wb', 0)
for i in range(5000):
sleep(sleep_time)
x = int(np.random.normal(sigma))
fobj.write('%c' % x)
fobj.close()