Array indices must be positive integers or logical values.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (1)
James Tursa
am 26 Mär. 2019
Bearbeitet: James Tursa
am 26 Mär. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!