フィルターのクリア

RK4 Function Code

2 ビュー (過去 30 日間)
John Brown
John Brown 2022 年 12 月 5 日
編集済み: Walter Roberson 2023 年 8 月 5 日
The issue occurs when running the function at the 'k_1 =' part of the code, the error message says "symbolic function expected 1 input but recieved 2"
function [x,y] = rk4(dydx,xo,xf,yo,h)
x = xo:h:xf ;
y = zeros(1,length(x));
y(1)= yo ;
for i = 1:(length(x)-1)
k_1 = dydx(x(i),y(i));
k_2 = dydx(x(i)+0.5*h,y(i)+0.5*h*k_1);
k_3 = dydx((x(i)+0.5*h),(y(i)+0.5*h*k_2));
k_4 = dydx((x(i)+h),(y(i)+k_3*h));
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
end
dydx = @(x,y) 3.*exp(-x)-0.4*y;
%[x,y] = rk4(dydx,0,100,-0.5,0.5); %plot(x,y,'o-');
end
  2 件のコメント
Torsten
Torsten 2022 年 12 月 5 日
Most probably the reason is that you didn't call "rk4" correctly.
John Brown
John Brown 2022 年 12 月 5 日
It shouldn’t have a th when called. When testing it didn’t. I forgot to delete that before posting here

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

回答 (2 件)

David Hill
David Hill 2022 年 12 月 5 日
dydx = @(x,y) 3.*exp(-x)-0.4*y;
[x,y] = rk4(dydx,0,100,-0.5,0.5);
plot(x,y,'o-');
function [x,y] = rk4(dydx,xo,xf,yo,h)
x = xo:h:xf ;
y = zeros(1,length(x));
y(1)= yo ;
for i = 1:(length(x)-1)
k_1 = dydx(x(i),y(i));
k_2 = dydx(x(i)+0.5*h,y(i)+0.5*h*k_1);
k_3 = dydx((x(i)+0.5*h),(y(i)+0.5*h*k_2));
k_4 = dydx((x(i)+h),(y(i)+k_3*h));
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
end
end
  2 件のコメント
John Brown
John Brown 2022 年 12 月 5 日
For this code i get the error "Error using indexing" and " error in line 6
David Hill
David Hill 2022 年 12 月 5 日
The above code runs without failure as you can see above. Did you save the function and run the 3-line script in the command line?

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


Steve Areola
Steve Areola 2023 年 8 月 5 日
clc
a=0;b=2;N=10;alph=0.5;
h=(b-a)/N;t(1)=a;w(1)=alph;
f=@(t,y) y-t^2+1;
for i=2:N+1
k1= h*f(t(i-1),w(i-1));
k2= h*f(t(i-1)+(h/2),w(i-1)+(k1/2));
k3= h*f(t(i-1)+(h/2),w(i-1)+(k2/2));
k4= h*f(t(i-1)+h,w(i-1)+k3);
w(i)=w(i-1)+(k1+2*k2+2*k3+k4)/6;
t(i)=a+(i-1)*h;
end
x=[t;w];
disp("t w")
t w
fprintf("%5.7f %5.7f\n",x)
0.0000000 0.5000000 0.2000000 0.8292933 0.4000000 1.2140762 0.6000000 1.6489220 0.8000000 2.1272027 1.0000000 2.6408227 1.2000000 3.1798942 1.4000000 3.7323401 1.6000000 4.2834095 1.8000000 4.8150857 2.0000000 5.3053630

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by