How do I create a create 'for' loop to compute time, position, velocity and add to running sum?
7 views (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
José-Luis
on 15 Oct 2012
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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!