The first function is performing the calculations but the second, when ran, won't graph the results

2 views (last 30 days)
I'm calling these two functions one after another from a menu created using switch (choice), the first one runs fine as I can see the reults come out but the second does not plot the results of the first.
function [x, v, t] = performcalcs(m, s1, ~, ~, t0, dt, t_total, ~, v, x, g)
i=1;
for t = t0: dt: t_total
F = - s1 .* x(i) - m .* g;
a = F ./ m;
v(i+1) = a .* dt + v(i);
x(i+1) = x(i) + v(i+1) .* dt;
i = i + 1;
end
end
function plotpos(t,x)
plot(t,x,'-');
title('Vertical position of mass');
xlabel('t[s]');
ylabel('x[m]');
end
  11 Comments

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 23 Jan 2021
Edited: Cris LaPierre on 23 Jan 2021
"Could it also be the way t is assigned?"
Yes, that is the issue. Your variable t is a loop counter, meaning it only ever has a single value assigned to it at a time. When you try to plot, t=t_total, not t0:dt:t_total. When you plot, then, it will plot each data point in x as a new series. Series are plotted as separate lines. Here, each of your lines is a single point, so you can't see them. To see this, in your figure window menu, select Edit > Plot Browser.
You don't even use t inside your for loop. Try this instead.
function [x, v, t] = performcalcs(m, s1, ~, ~, t0, dt, t_total, ~, v, x, g)
t = t0: dt: t_total
for i=1:length(t)
F = - s1 .* x(i) - m .* g;
a = F ./ m;
v(i+1) = a .* dt + v(i);
x(i+1) = x(i) + v(i+1) .* dt;
end
end
  2 Comments
Cris LaPierre
Cris LaPierre on 23 Jan 2021
Edited: Cris LaPierre on 23 Jan 2021
x has one more data point than t
x(i+1) = x(i) + v(i+1) .* dt;
^^ % i+1
Try starting at i=2, and use i-1 and i instead of i and i+1
for i=2:length(t)
F = - s1 .* x(i-1) - m .* g;
a = F ./ m;
v(i) = a .* dt + v(i-1);
x(i) = x(i-1) + v(i) .* dt;
end
Cris LaPierre
Cris LaPierre on 24 Jan 2021
Addition comments the OP made but has since deleted
This seems to be progress but now I am getting an error saying:
Error using plot
Vectors must be the same length.
Error in Weight>plotpos (line 62 )
plot(t,x,'-');
Error in Weight (line 36 )
plotpos(t,x); %plot position
Thank you so much for your help !
That works now

Sign in to comment.

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!