Index must be a positive integer or logical
6 views (last 30 days)
Show older comments
I'm am working on modeling the physical pendulum using 4th Runge-Kutta Method and and getting the error
"Attempted to access F_t_theta_v(1,-0.0885,0.8); index must
be a positive integer or logical. Error in PhyFinal (line 42)
k_v1 = h * F_t_theta_v( t(i), theta(i), v(i) );"
Not sure what is going on or why it's not working. Any explaination would be helpful!
%Define Variables
w0 = 1;
alpha = 0.2;
f = 0.52;
w = 0.666;
%define step size
h = 1;
%set t from 1 to 100 seconds
t = 1:h:100;
%Create placement to put values generated
theta = zeros ( 1 , length(t) );
v= zeros ( 1 , length(t) );
k_v1=zeros ( 1 , length(t) );
k_theta1=zeros ( 1 , length(t) );
%first initial conditions
theta(1)=-0.0885;
v(1)=0.8;
%Function.
F_t_theta_v = -w0^2 * sin(theta) - alpha * v + f * cos(w*t);
%Apply 4th RK
for i=1:(length(t)-1);
k_v1 = h * F_t_theta_v( t(i), theta(i), v(i) );
k_theta1 = h * v;
k_v2 = h * F_t_theta_v ( (t(i) + 0.5 * h), (theta(i) + 0.5 * k_theta1), (v + 0.5 * k_v1) );
k_theta2 = h * (v + k_v1);
k_v3 = h * F_t_theta_v ( (t(i) + 0.5 * h), ( theta (i) + 0.5 * k_theta2), (v + k_v1) );
k_theta3 = h * ( v + k_v2 );
k_v4 = h * F_t_theta_v ( ( t(i) + h ), ( theta(i) + k_theta3), ( v + k_v1));
k_theta4 = h * ( v + k_v3 );
dtheta = 1/6 * (k_theta1 + 2 * k_theta2 + 2 * k_theta3 + k_theta4);
dv = 1/6 * (k_v1 + 2 * k_v2 + 2 * k_v3 + k_v4);
theta(i + h) = theta(i) + dtheta;
v (i + h) = v(i) + dv;
end
%plot theta(t), might change to 'x' for consistency', and v(t)
figure(1);
plot ( v,theta)
0 Comments
Accepted Answer
Star Strider
on 29 Nov 2014
%Function.
F_t_theta_v = @(t,theta,v) -w0^2 * sin(theta) - alpha * v + f * cos(w*t);
Change the variables in the argument list in ‘@(t,theta,v)’ if I got it wrong. (I used the name of your function as a clue!) Your function should work then. It should pick up the other variables it needs from your workspace, but they have to be defined before you define the function.
2 Comments
Star Strider
on 29 Nov 2014
Edited: Star Strider
on 29 Nov 2014
Good!
The new problem is with ‘dtheta’. You defined ‘v’ as a vector, and that propagates through to ‘dtheta’. You defined ‘theta(i+h)’ as a scalar, and you cannot assign a vector to a scalar.
If you want to define it as a vector,
theta(i + h, :) = theta(i) + dtheta;
should work.
If you don’t want to define it as a vector, you need to select one element of ‘dtheta’ instead of the entire vector.
More Answers (1)
Azzi Abdelmalek
on 29 Nov 2014
Check your indices, if a is an array you can't write
a(1.8)
the index must be a positive integer or logical
0 Comments
See Also
Categories
Find more on Assembly 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!