Plotting to multiple GUI axes simultaneously using a for loop

7 次查看(过去 30 天)
Hi,
I am trying to build a GUI to plot real-time data from an Arduino. The code needs to read the values in from four analog pins and plots the data on each of the 4 axes in the Matlab GUI, respectively. The code I have at the moment works, however it is rather slow. Can anyone provide a means to make this faster/remove inefficiencies or any other assistance would be helpful? The code is as follows:
x1=0;
x2=0;
x3=0;
x4=0;
for k=1:1:100
%plot 1
A1=readVoltage(a,'A1');
x1=[x1,A1];
plot(handles.axes1,x1,'LineWidth',2);
grid on;
drawnow;
%plot 2
A2=readVoltage(a,'A2');
x2=[x2,A2];
plot(handles.axes2,x2,'LineWidth',2);
grid on;
drawnow;
%plot 3
A3=readVoltage(a,'A3');
x3=[x3,A3];
plot(handles.axes3,x3,'LineWidth',2);
grid on;
drawnow;
%plot 4
A4=readVoltage(a,'A4');
x4=[x4,A4];
plot(handles.axes4,x4,'LineWidth',2);
grid on;
drawnow;
pause(0.01);
end

采纳的回答

OCDER
OCDER 2018-7-9
编辑:OCDER 2018-7-10
x = zeros(4, 101); %Preallocation is much faster
Px = gObjects(1, 4);
for c = 1:4 %Initilize all your plots, for 4 pins
Px(c) = plot(handles.(['axes' num2str(c)]), 0, 'LineWidth', 2); %Store your plot handles
grid on;
end
for k = 2:101 %Did k to 101 since it looks like you want to keep the 1st point as a 0
for c = 1:4
x(c, k) = readVoltage(a, ['A' num2str(c)]);
set(Px(c), 'XData', 1:k, 'YData', x(c, 1:k)); %Setting the XData and YData directly to prevent redrawing plot from scrap.
end
drawnow; %Do only 1 drawnow, instead of 4 drawnow you had before
end
Note that instead of 4 plots, you could just have 1 plot with 4 lines for a little extra speed and simplicity in GUI.
  4 个评论
TCull
TCull 2018-7-9
Wonderful! Everything working now. I did however changer the second argument of plot function from a [] to a 0 in Px(c) = plot(....) as it gave "In an assignment A(:) = B, the number of elements in A and B must be the same."
But everything is working wonderfully. So much smoother.
Thank you so much for your help!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Performance 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by