Plotting from a for loop?
2 ビュー (過去 30 日間)
古いコメントを表示
I'm trying to plot the solution to these equations from a for loop with different values of t, but Matlab is ignoring all the previous solutions to these three equations and only returning with the final value. Any help? This is what I have so far.
c0=input('c0=..... ');
c1=input('c1=..... ');
c2=input('c2=..... ');
c3=input('c3=..... ');
c4=input('c4=..... ');
c5=input('c5=..... ');
for t=0:0.1:3
a=c0+(c1*t)+(c2*t^2)+(c3+t^3)+(c4*t^4)+(c5*t^5); %angle
v=c1+(2*c2*t)+(3*c3*t^2)+(4*c4*t^3)+(5*c5*t^4); %velocity
acc=(2*c2)+(6*c3*t)+(12*c4*t^2)+(20*c5*t^3); %acceleration
end
plot(t,a,t,v,t,acc)
0 件のコメント
回答 (3 件)
Star Strider
2016 年 1 月 26 日
You can probably vectorise your equations easily:
t=0:0.1:3;
a=c0+(c1*t)+(c2*t.^2)+(c3+t.^3)+(c4*t.^4)+(c5*t.^5); %angle
v=c1+(2*c2*t)+(3*c3*t.^2)+(4*c4*t.^3)+(5*c5*t.^4); %velocity
acc=(2*c2)+(6*c3*t)+(12*c4*t.^2)+(20*c5*t.^3); %acceleration
plot(t,a,t,v,t,acc)
I plugged in random values for the constants to verify that this works.
0 件のコメント
Image Analyst
2016 年 1 月 26 日
You need to index those values:
all_t = 0:0.1:3
for k = 1 : length(all_t)
t = all_t(k);
a(k) = c0+(c1*t)+(c2*t^2)+(c3+t^3)+(c4*t^4)+(c5*t^5); %angle
v(k) = c1+(2*c2*t)+(3*c3*t^2)+(4*c4*t^3)+(5*c5*t^4); %velocity
acc(k) = (2*c2)+(6*c3*t)+(12*c4*t^2)+(20*c5*t^3); %acceleration
end
plot(all_t, a, 'r*-', 'LineWidth', 2, 'MarkerSize', 9);
hold on;
plot(all_t, v, 'bo-', 'LineWidth', 2, 'MarkerSize', 9);
plot(all_t, acc, 'md-', 'LineWidth', 2, 'MarkerSize', 9);
0 件のコメント
dpb
2016 年 1 月 26 日
Use the vectors, Luke... :)
You're overwriting each pass thru the loop; you can make an array and populate it, but "the Matlab way" is to use the vectorized solution...
t=0:0.1:3;
a=c0 + c1*t + c2*t.^2 + c3*t.^3 + c4*t.^4 + c5*t.^5;
Similarly for the remaining. NB: the "dot operator" for the exponential terms to use the element-by-element computation rather than matrix power.
And, you can simplify further if, instead of separate named variables you use an array of coefficients...
c=[c5 c4 c3 c2 c1 c0]; % coefficients in an array in descending power order
a=polyval(c,t); % evaluate for t vector locations
Will leave as "exercise for the student" but also investigate
doc polyder
for computing the derivatives analytically from the original poly coefficient vector to get the remaining values.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!