在matlab上用x轴上的定时器绘图

时间:2016-03-24 15:39:27

标签: matlab matlab-guide

我有一个Matlab代码,它根据循环迭代绘制变量值。

我已将随机值视为此示例的变量值。

function varargout = myplot(varargin)

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @myplot_OpeningFcn, ...
                   'gui_OutputFcn',  @myplot_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before myplot is made visible.
function myplot_OpeningFcn(hObject, eventdata, handles, varargin)

handles.output = hObject;
% Update handles structure
guidata(hObject, handles);


function varargout = myplot_OutputFcn(hObject, eventdata, handles) 

varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
axes(handles.axes1);
iif = 0;
i = 1;
y = 0;
while (i < 1000)
    yf = rand(1);
    y = [y, yf];
    iif = [i,iif];
    i = i + 1;
    plot(iif,y);
    pause(0.001);
end

如何将iif = [i,iif];替换为计时器?

我想要的是根据时间(以秒为单位)绘制的数据,而不是数据与循环迭代。任何人都有任何想法?感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用tictoc来跟踪已过去的秒数。 tic启动计数器,所有对toc的连续调用都会返回自上一个tic以来经过的秒数。

iif = 0;
i = 1;
y = 0;

hplot = plot(iif, y);
xlabel('Elapsed Time (s)')
ylabel('Value')

% Force a graphics refresh so that isn't counted in our elapsed time
drawnow

% Start the timer
tic

while (i < 1000)
    yf = rand(1);
    y = cat(2, y, yf);

    % Call toc to get the current elapsed time
    iif = cat(2, iif, toc);

    i = i + 1;

    set(hplot, 'xdata', iif, 'ydata', y);
    pause(0.001)
end

enter image description here

作为旁注,您还可以将循环编写为for循环并预先分配所有变量,从而提高性能。

nIterations = 1000;
iif = nan(nIterations, 1);
y = nan(nIterations, 1);

hplot = plot(iif, y);

tic

for k = 1:nIterations
    y(k) = rand(1);
    iif(k) = toc;

    set(hplot, 'XData', iif, 'YData', y)
    pause(0.001)
end