0

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.

3
  • with plot(time,theta(1:numel(time))) I guess. If not, please include a minimal executable example. Commented Jul 26, 2017 at 6:50
  • 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? Commented Jul 26, 2017 at 7:36
  • 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. Commented Jul 26, 2017 at 11:54

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Thank you for the suggestion. However, when I tried this, it still gives me an empty plot. I am unable to see anything at all being plot.
Can you post your code? When I launch this example as-is, it plots theta as a function of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.