0
votes

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.

2
with plot(time,theta(1:numel(time))) I guess. If not, please include a minimal executable example. - Robert Seifert
I gather that time is a single value, not an array, is that so? It is not clear what you want to do. Maybe plot the last value of theta against current time, while keeping the "history" of the plot? - Zep
time is a scalar, theta is an array that stores 5 values at every time instant. So, theta is 1*5 array. At every instant, I want those 5 variables whose value is stored in theta to be plot. At the next time step, I need the 5 variables at (t+1) to be plot and connected (through a line and not discontinuous) with the previous instant data-points. - user3856486

2 Answers

1
votes

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
0
votes

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.