Question about the error "Attempted to access (0.5); index must be a positive integer or logical."
Show older comments
I created matlab code in m file like below
D_s = 0.6;
T_d = 0.2;
T_c = 0.5;
x_sd = 0.5*D_s;
x_ed = 0.5*D_s;
g = 9.8;
z = 0.9;
m = 40;
for k = 1:1:10
for t = k*T_c:0.1:(k*T_c)+T_d
x_h(t) = k*D_s+(x_ed*(T_d+k*T_c-t)/T_d)+((D_s-x_sd)*(t-k*T_c)/T_d);
end
for t = k*T_c+T_d:0.1:(k+1)*T_c
x_h(t) = k*D_s+(D_s-x_ed*((k+1)*T_c-t)/T_c-T_d)+((D_s+x_ed)*(t-k*T_c-T_d)/T_c-T_d);
end
end
for t = k*T_c:0.1:(k+1)*T_c
p_x = x_h(t)-(g/z)*diff(diff(x_h(t)));
F_gr = m*(diff(diff(x_h(t)))-g);
end
After writing this code, I ran this m file, but no results came out. Only the error came out
Attempted to access (0.5); index must be a positive integer or logical.
Error in CoMtraj (line 11)
x_h(t) = k*D_s+(x_ed*(T_d+k*T_c-t)/T_d)+((D_s-x_sd)*(t-k*T_c)/T_d);
What should I change in this code? I should observe the continuous function x(t) with respect to the time variable t
Answers (1)
Walter Roberson
on 2 Sep 2015
Change your loops. For example where you have
for t = k*T_c:0.1:(k*T_c)+T_d
x_h(t) = k*D_s+(x_ed*(T_d+k*T_c-t)/T_d)+((D_s-x_sd)*(t-k*T_c)/T_d);
end
change it to
tvals = k*T_c:0.1:(k*T_c)+T_d;
for tidx = 1 : length(tvals);
t = tvals(tidx);
x_h(tidx) = k*D_s+(x_ed*(T_d+k*T_c-t)/T_d)+((D_s-x_sd)*(t-k*T_c)/T_d);
end
Categories
Find more on Matrix Indexing 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!