The first function is performing the calculations but the second, when ran, won't graph the results
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Cris LaPierre
2021년 1월 23일
편집: Cris LaPierre
2021년 1월 23일
"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
Cris LaPierre
2021년 1월 23일
편집: Cris LaPierre
2021년 1월 23일
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
2021년 1월 24일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Performance에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!