필터 지우기
필터 지우기

Array indices must be positive integers or logical values.

조회 수: 2 (최근 30일)
Alexa Shumaker
Alexa Shumaker 2019년 3월 26일
편집: Walter Roberson 2019년 3월 26일
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
James Tursa
James Tursa 2019년 3월 26일
Did you also see that I changed the upper bound to n-1?

댓글을 달려면 로그인하십시오.

카테고리

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