Error of index exceeds the number of array elements, not sure why. Time sensitive, but not important
1 view (last 30 days)
Show older comments
Max Bailey
on 10 Apr 2020
Commented: Walter Roberson
on 10 Apr 2020
I have a project for college class so this function is set up specifically for the problem. We have to do the euler equation without using the integrated euler functions. If there's any questions I can explain them, I'm not too sure what all info to give. Everything works fine but at the end I get this error:
Index exceeds the number of array elements (11).
Error in euler1 (line 15)
V(j+1)=V(j)+step*func1(T(j+1),V(j));
Here are the inputs
funct1=@(t)3*sin(t)^2;
funct2=@(t,V)3*sin(t)^2-3*(1.35*V^(1/3)-1)^1.5;
tstart=0;
tend=10;
y0=0.9;
yo=1;
s=1.6;
The steps are 1, 0.5, 0.1, 0.05, but I didn't know how to implement that so I just do it one at a time.
This specific error is for a step of 1, but other steps just change the number in the error.
And the function
function euler1(func1,func2,tstart,tend,step,y0,yo,s)
%Function 1 is with output, function 2 is without
steps=(tend-tstart)/step+1;
Y=zeros(1,steps);
V=zeros(1,steps);
T=tstart:step:tend;
V0=(pi*y0^3)/(3*s^2);
Y(1)=y0;
V(1)=V0;
for j=1:steps
if Y(j)<yo
V(j+1)=V(j)+step*func2(T(j+1));
Y(j+1)=((3*s^2*V(j+1))/(pi))^(1/3);
else
V(j+1)=V(j)+step*func1(T(j+1),V(j));
Y(j+1)=((3*s^2*V(j+1))/(pi))^(1/3);
end
end
end
It used to give me the values at the end after the error anyways, but now I can't get the values out of it and I need to make tables of the outputs.
1 Comment
Walter Roberson
on 10 Apr 2020
Thank you for differentiating between time sensitive and important!! +1!
Accepted Answer
Walter Roberson
on 10 Apr 2020
You index T(j+1). For that to work the maximum value for j cannot exceed one less than the number of elements in T, so make sure that your for loop stops early enough.
Also because of floating point roundoff, the way you calculate steps is not guaranteed to exactly equal the length of T. It would be safer if you calculate T first and then assign steps based on length(T)
2 Comments
Walter Roberson
on 10 Apr 2020
Well first make the change on how you calculate steps. Then change the for loop so it ends one earlier.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!