When I try to run a while loop for kinematcs I get the error:'index exceeds number of array elements'.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Sam Potter
el 9 de Mzo. de 2020
Comentada: Ameer Hamza
el 9 de Mzo. de 2020
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.
4 comentarios
Ahmed Anas
el 9 de Mzo. de 2020
I have found the error, but its important that what you want from this code.
In while loop you are using the whole h matrix, better to use that particular value i.e. h(1).. and i suggest you to use a combination of for and if loop instead of while loop. If you explain me what you want then able to do this for you.
Thanks
Ahmed Anas
el 9 de Mzo. de 2020
Error lies in these two lines..
h(i+1)=150000-(g(i)*(t(i+1))^2)
g(i)=(40*10^7)/(6371+h(i+1))^2
In the h formula, it is using g which is calculated in the next step, so matlab is unable to solve it..
Hope you got the point
Respuesta aceptada
Ameer Hamza
el 9 de Mzo. de 2020
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
2 comentarios
Ameer Hamza
el 9 de Mzo. de 2020
These are the changes I made.
g(i+1)=(40*10^7)/(6371+h(i+1))^2;
The next iteration needed to use the value of g(i+1), but you were assigning it to g(i), therefore you got error "Index exceeds number of array elements", the element was not present at next iteration.
Same with
v(i+1)=g(i)*t(i+1);
Infact, i think following might be correct
v(i+1)=g(i+1)*t(i+1);
You can compare both and see which of them seems correct.
Last, I changed condition of while loop h(end)>=100000. You were comparing complete array, whereas only last element needed to be compared.
Más respuestas (0)
Ver también
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!