How can I connect the points on my graph?

4 views (last 30 days)
I have written code to plot graphs for the Hindmarsh-Rose equation, but, I have a few problems with it.
I can either plot the point for the graph inside the loop function, which is quick but the points are not connected. Or i can plot the points outside the loop function in which the points end up connected but to get the results it takes a long time.
I have tried a few different things like trying to store the values in an array so i can later use them in the code, but I assume I have not used them correctly as they dont work.
I wasn't sure what part of the code to add to help give a better picture so I decided to put it all in. Any suggestions would be appreciated.
a = 1.0;
b = 3.0;
c = 1.0;
d = 5.0;
I = 3.25;
r = 0.005;
s = 4.0;
p0 = -1.6;
dt = 1;
t = 0;
p = -1.6;
q = 4.0;
n = 2.75;
scale = 0.001;
ms = 50;
iterations = ms * 1000;
count = 0;
arrayp = zeros(1, ms);
for i = 0:iterations
remainder = mod(i,1000);
if remainder == 0
fprintf('t = %.4f p = %.4f q = %.4f n = %.4f do = %.4f \n', t, p, q, n, do)
arrayp(count, :) = (p);
%Using this plot function works faster but the plots don't connect
%plot(t,p, '-xr')
%hold all
end
dp = q - (a*p.^3) + (b*p.^2) - n + I ;
dq = c - (d*p.^2) - q;
dn = r*(s*(p - p0) - n);
p = p + (dp * scale);
q = q + (dq * scale);
n = n + (dn * scale);
t = t + (dt * scale);
%Using this plot function connects the points but it is slow
%plot(t,p,'-xr')
%hold all
end

Accepted Answer

Adam Danz
Adam Danz on 15 Jan 2021
Edited: Adam Danz on 15 Jan 2021
You need to store the values within the loop and then plot them after the loop.
The changes will look something like this incomplete example below. Importantly, i cannot start with 0 since you'll use it as an index.
t = nan(1,iterations);
p = nan(1,iterations);
t = 0;
p = -1.6;
for i = 2:iterations
...
...
...
p(i) = p(i-1) + (dp * scale);
...
t(i) = t(i-1) + (dt * scale);
end
plot(t,p,'-xr')
  1 Comment
Jonathan Dalby
Jonathan Dalby on 16 Jan 2021
Thanks, this has helped a lot, had a few problems but i managed to figure it out and its working great.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!