フィルターのクリア

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?
Alexa Shumaker
Alexa Shumaker 2019 年 3 月 26 日
Thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by