How do I create a create 'for' loop to compute time, position, velocity and add to running sum?
古いコメントを表示
for t=[0:0.1:8]
p(t)=(A*t^4)-(B*t^3)+(C*t^2)-(D*t)+E;
v(t)=(4*A*t^3)-(3*B*t^2)+(2*C*t)-D;
end
This is what I have so far. I need to determine position and velocity over the range 0<=t<=8 in time steps of .1 seconds. When I try running this I get an error that it can't access p(0). How do I make this code work as intended?
回答 (1 件)
José-Luis
2012 年 10 月 15 日
Indexes in Matlab start with one, not zero. which_ever_array(0) will return an error. In your example, you could, amongst other things, add a counter variable:
counter = 1;
for t=[0:0.1:8]
p(counter)=(A*t^4)-(B*t^3)+(C*t^2)-(D*t)+E;
v(counter)=(4*A*t^3)-(3*B*t^2)+(2*C*t)-D;
counter = counter + 1;
end
Note that even then it would be a good idea to preallocate
counter = 1;
p = NaN * ones(numel(0:0.1:8),1);
v = p;
for t=[0:0.1:8]
p(counter)=(A*t^4)-(B*t^3)+(C*t^2)-(D*t)+E;
v(counter)=(4*A*t^3)-(3*B*t^2)+(2*C*t)-D;
counter = counter + 1;
end
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!