MATLAB: When I try to run a while loop for kinematcs I get the error:’index exceeds number of array elements’.

errorMATLABwhile loop

h(1)=150000; %initial height
g(1)=(40*10^7)/(6371+h(1))^2; %acceleration dependant on height
i=1; %loop counter
dt=0.005; %time step
t(1)=0; %initial time
v(1)=g(1)*t(1); %velocity
while h>=100000
t(i+1)=t(i)+dt;
h(i+1)=150000-(g(i)*(t(i+1))^2);
g(i)=(40*10^7)/(6371+h(i+1))^2;
v(i)=g(i)*t(i+1);
i=(i+1);
end
When i try to run this loop i get the error 'Index exceeds number of array elements (1)'. Any help would be appriciated. Ideally I would like to be able see the last values of g and v when h>=100000.

Best Answer

It appears there is an issue with the indexing of g and v inside the while loop. The condition of while loop also seems wrong. Try this
h(1)=150000; %initial height
g(1)=(40*10^7)/(6371+h(1))^2; %acceleration dependant on height
dt=0.005; %time step
t(1)=0; %initial time
v(1)=g(1)*t(1); %velocity
i=1; %loop counter
while h(end)>=100000
t(i+1)=t(i)+dt;
h(i+1)=150000-(g(i)*(t(i+1))^2);
g(i+1)=(40*10^7)/(6371+h(i+1))^2;
v(i+1)=g(i)*t(i+1);
i=i+1;
end
Related Question