4th order Runge-Kutta Method Help

11 visualizaciones (últimos 30 días)
WhatIsMatlab-
WhatIsMatlab- el 20 de Abr. de 2016
Editada: WhatIsMatlab- el 23 de Abr. de 2016
Below is my code for a 4th order Runge-Kutta but I keep getting an error and I don't see what I am doing wrong. I was hoping somebody could help point me in the right direction to fix my code.

Respuesta aceptada

James Tursa
James Tursa el 20 de Abr. de 2016
Editada: James Tursa el 20 de Abr. de 2016
You never set the z2 elements inside your loop, so on the second iteration when z2(i-1) is used (with i=3) z2(2) does not exist. I am guessing you need to add a line like this after setting z1(i):
z2(i) = z2(i-1)+((1/6)*(k1z2+2*k2z2+2*k3z2+k4z2));
Also, it appears you have a typo in your z1(i) assignment. That last * should be a + instead. E.g.,
z1(i) = z1(i-1)+((1/6)*(k1z1+2*k2z1+2*k3z1*k4z1));
should be
z1(i) = z1(i-1)+((1/6)*(k1z1+2*k2z1+2*k3z1+k4z1));
Finally, as a readability advice I would suggest you put some spaces in your code. E.g., I think this is much more readable (and easier to spot bugs):
z1(i) = z1(i-1) + (1/6) * (k1z1 + 2*k2z1 + 2*k3z1 + k4z1);
z2(i) = z2(i-1) + (1/6) * (k1z2 + 2*k2z2 + 2*k3z2 + k4z2);
  1 comentario
WhatIsMatlab-
WhatIsMatlab- el 20 de Abr. de 2016
Thank you!! That did the trick. I took your advice on adding the spacing. You are 100% right it makes it a lot easier to see what is happening in my code. Thank you again.

Iniciar sesión para comentar.

Más respuestas (1)

Torsten
Torsten el 20 de Abr. de 2016
dz2dx = @(z1,z2) 2*z2 5*z1;
There is no connector between z2 and 5 in the expression above.
Best wishes
Torsten.
  1 comentario
WhatIsMatlab-
WhatIsMatlab- el 20 de Abr. de 2016
Sorry there should be a plus sign there. But that doesn't fix the problem. That was an error from copying the code over.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by