Array indices must be positive integers or logical values.

2 次查看(过去 30 天)
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

回答(1 个)

James Tursa
James Tursa 2019-3-26
编辑:James Tursa 2019-3-26
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 个评论

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by