Having trouble plotting in real-time
Show older comments
Hi, I am new to MATLAB (student) and I have a school assignment where I have to plot a Euler-approximation in real-time but I am having a bit of trouble. My real-time plot seems to just draw a straight line for whatever reason but if I plot it normally it draws my curves just fine.
Here is my code:
% Euler's Method
% Initial conditions and setup
g = 25;
h = 0.1; % step size
M = 10; % Number of cars
x = 0:h:40; % the range of x (time)
n = numel(x); % the number of timesteps
posMat = zeros(M,n); % Matrix that holds positions of each car (car = row, time = column)
for i=1:M
posMat(i,1) = 10*i; % the initial positions for the cars
end
for t=2:(n-1)
% Calculate position of all cars EXCEPT car M (using the first
% equation)
for c=1:(M-1)
f = carFunc(posMat(c+1,t) - posMat(c,t));
posMat(c,t+1) = posMat(c,t) + h * f;
end
% Calculate positon of car M (first car in queue) here:
% x_M^(n+1) = x_M^n + h*g
posMat(M,t+1) = posMat(M,t) + h*g;
end
hold on
for i=1:n
plot(zeros(M,1),posMat(:,i),'r*');
axis([-1 1 0 1000])
drawnow
pause(h)
end
hold off
function output = carFunc(x)
if (x >= 75)
output = 25;
else
output = x/3;
end
end
With this code I just get a plot with a straight red line that looks like this:

The plotting code
hold on
for i=1:n
plot(zeros(M,1),posMat(:,i),'r*');
axis([-1 1 0 1000])
drawnow
pause(h)
end
Was provided to me by the teachers and it SHOULD work... but clearly doesn't! What am I doing wrong?
My own (non-realtime) plotting code
hold on
for i=1:M
plot(x,posMat(i,:))
end
hold off
works just fine though.
The resulting plot from that code looks like this:

Help? Thanks!
Accepted Answer
More Answers (0)
Categories
Find more on Graphics Performance 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!