Reputation: 547
I am trying to plot variables dynamically in MATLAB. I have an array (set of states) that needs to be plotted with time. I tried plot(time,theta), where theta is a 1*5 array. With this command, I get an error saying that theta should be a scalar because time is a scalar. I then tried using for-loop to plot(time,theta(i)). The problem with this is that I get data points at discrete time intervals on my plot. However I need a continuous plot. I wonder how this can be done.
Upvotes: 0
Views: 1810
Reputation: 1576
Let's see if I get this straight. Time is updated at every step, and theta are five different variables that also get updated. This should work for you:
% Use your own time variable
time = 1:100;
figure; hold on;
h = cell(5,1); % Handles of animated lines
colors = 'rgbkm'; % Colors of lines
for t = time
theta = randn(5,1);
if isempty(h{1})
% Initialize plot
for k = 1 : 5
h{k} = animatedline(t , theta(k) , 'LineStyle' , '-' , 'Color' , colors(k));
end
else
% Update plot with new data
for k = 1 : 5
addpoints(h{k}, t , theta(k));
end
end
% Update plot
drawnow
end
The object animatedline
was introduced in R2014b. You can still do something similar with a conventional plot and updating the XData and YData properties of the lines at each loop.
Upvotes: 0
Reputation: 429
You need to use hold on
when plotting.
For example:
time = 1;
theta = [1:100];
figure
for i=1:100
plot(time, theta(i),'r.')
hold on %--> Keeps the previous data in your plot
time = time + 1;
end
Upvotes: 1