Multiple Y variables in RealTime
Show older comments
I am attempting to read multiple variables from an arduino and plot in real time. The data is from an gyroscope so I have 3 Axis data so am trying to plot all three Y variables. I am using the following code:
s = serial('COM4', 'baudrate', 115200);
plotTitle='Gryoscope';
xLabel='Time (s)';
yLabel='Distance';
plotGrid = 'on';
delay = .01;
time = 0;
distance1 = 0;
count = 0;
plotGraph = plot(time,distance1);
grid(plotGrid);
fopen(s);
tic
while ishandle(plotGraph)
dist = str2num(fscanf(s))
count = count + 1;
time(count) = toc;
distance1(1,count) = dist(1);
distance1(2,count) = dist(2);
distance1(3,count) = dist(3);
set(plotGraph(1),'XData',time,'YData', distance1);
axis([time(count)-10 time(count) 0 10]);
pause(delay);
end
I get an error at "set(plotGraph(1),'XData',time,'YData', distance1);" as distance1 variable is too large. I have tried converting to cell variable and plotting separately with hold on but neither are working. Is there any way to overcome this to plot both Y variables on the same graph in real time?
Answers (2)
Neuropragmatist
on 6 Aug 2019
0 votes
If you mean that distance1 has too many elements to be plotted you could just downsample it - i.e. by taking every 10th or 100th point instead of every point. But that seems unlikely because Matlab can plot a lot of data points.
If you mean that distance1 doesn't match the size of 'time', then I don't know why that would be the case.
What is the error you get specifically?
1 Comment
Andrew Mason
on 6 Aug 2019
Steven Lord
on 6 Aug 2019
distance1 is not a vector, it is a matrix.
If you're plotting one line in your call the plot and want to update it with the latest vector stored in distance1, set the YData to distance1(:, count) rather than the entire distance1 matrix.
If you're plotting multiple lines with one call to plot, the output from plot will be a vector of line handles. You can't set the YData property of that vector to a matrix the way you're trying to. You'll need to either set the properties of each element of the vector of line handles individually or use a cell array.
h = plot((1:10).', rand(10, 3)) % h is 3-by-1
for iteration = 1:10
newYData = {rand(1, 10); rand(1, 10); rand(1, 10)}; % You could use mat2cell here
set(h, {'YData'}, newYData)
pause(1) % So you can see the change
end
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!