Array indices must be positive integers or logical values.
Afficher commentaires plus anciens
Writing function for Runge Kutta 4th order. ERROR --> Array indices must be positive integers or logical values.
command window call is
dydx = @(x,y) (1+4*x)*sqrt(y)
RungeKutta(dydx, 0, 1,0.25,1)
code below
function RungeKutta(f, L, U,h,y0)
%f = function
% L = lower bound
% U = upper bound
% y0 = inital condition y value
%h = step size
t = L:h:U;
n = length(t);
% need for loop
k1 = zeros (1,n);
k2 = zeros (1,n);
k3 = zeros (1,n);
k4 = zeros (1,n);
y = zeros(1, n);
for i = 0: n
k1(i) = f(t(i),y(i));
k2(i) = f(t(i)+0.5*h,y(i)+0.5*k1(i)*h);
k3(i) = f(t(i) + 0.5*h, y(i)+0.5*k2(i)*h);
k4(i) = f(t(i) + h, y(i) + k3(i)*h);
y(i+1) = y(i) + (1/6)*(k1(i)+2*k2(i) + 2*k3(i)+k4(i))*h;
end %end of fo loop
hold on
title('Runge-Kutta Method')
xlabel('X axis')
ylabel('Y axis')
plot(t, f(t),'b', x, y, 'r')
legend('Original Plot', 'True Plot')
end % end of function
Réponses (1)
James Tursa
le 26 Mar 2019
Modifié(e) : James Tursa
le 26 Mar 2019
At least two problems. First, you need to start your for loop indexing at 1 instead of 0:
for i = 1: n-1 % ending at n-1 so that y stays at n elements
Second, you don't set the initial state of y before entering the loop. You need something like this prior to the loop:
y(1) = y0;
3 commentaires
Alexa Shumaker
le 26 Mar 2019
James Tursa
le 26 Mar 2019
Did you also see that I changed the upper bound to n-1?
Alexa Shumaker
le 26 Mar 2019
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!