Index exceeds the number of array elements for runge kutta method

clear all
close all
clc
h =.5; % set the step size
x =[0,4]; % set the interval of x
y = zeros(1,length(x));
yo = 0; % set the intial value for y
n = length(x)-1;
f =@(x,y)-2*x^3+12*x^2-20+8.5; %insert function to be solved
for i = 1:4
k1 = f(x(i),y(i));
k2 = f(x(i)+.5*h,y(i)+.5*k1*h);
k3 = f(x(i)+.5*h,y(i)+.5*k2*h);
k4 = f(x(i)+h,y(i)+k3*h);
y(i+1) = y(i)+((k1+2*k2+2*k3+k4)/6)*h;
end
[t,y_check] = ode45(f,x,2);
plot(x,y)
title('Eulers Method')
figure
plot(x,y_check)
title('ode45 Check')

1 Commento

I am trying to solve th ODE using the runge Kuuta 4th order method, but keep getting this error in my code. Any suggesttions what I need to fix?

Accedi per commentare.

 Risposta accettata

Your loop goes from 1:4
for i = 1:4
k1 = f(x(i),y(i));
but your vectors only have 2 elements.
x =[0,4]; % set the interval of x
y = zeros(1,length(x));
Did you mean something like this?
x=linspace(0,4,100);

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 24 Apr 2021

Risposto:

DGM
il 24 Apr 2021

Community Treasure Hunt

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

Start Hunting!

Translated by