変数の値がワークスペ​ースでは正しい値が表​示されるが,実行する​と0になってしまう.

12 vues (au cours des 30 derniers jours)
拓
le 23 Juin 2023
Commenté : le 24 Juin 2023
t = 0:0.01:1.7;
A = func_RK(t,2.072)
このときのAの値がワークスペースでは2.071,2.0735...となるのですが,実行した結果は0,0,...となってしまいます.
ライブ関数1
関数 func_RK
1階の微分方程式に対して Runge-Kutta の計算を行うための下請け関数
引数: 時間ベクトル t, および x の初期値 x0
戻り値: ベクトル x
function x = func_RK(t, x0)
% 刻み時間Δtの設定
del_t = t(2) - t(1);
% ベクトル t をコピーして, 漸化式で計算する x を作成
x = t;
% 初期値
x(1) = x0;
% 漸化式
for i = 1:(length(t)-1)
% 式(10.16)
dx0 = func(x(i))*del_t;
% 式(10.17)
dx1 = func(x(i)+dx0/2)*del_t;
% 式(10.18)
dx2 = func(x(i)+dx1/2)*del_t;
% 式(10.19)
dx3 = func(x(i)+dx2)*del_t;
% 式(10.20)
x(i+1) = x(i) + (dx0 + 2*dx1 + 2*dx2 + dx3)/6;
end
end
ライブ関数2
Runge-Kuttaの計算で傾きを与える関数
引数: x
戻り値: x(t) の傾き, つまり f(x) = dx/dt
function f = func(x)
A = 2; B = 1;
% f(x) = dx/dt
f = -A*x + B*x^2;
end
  2 commentaires
Kojiro Saito
Kojiro Saito le 24 Juin 2023
実行した結果が0,0,.になるというのが再現できません。
下記の通り問題なく実行できているのでコードは正しくできているようです。
t = 0:0.01:1.7;
A = func_RK(t,2.072)
A = 1×171
2.0720 2.0735 2.0750 2.0766 2.0782 2.0799 2.0816 2.0833 2.0850 2.0868 2.0886 2.0905 2.0924 2.0944 2.0964 2.0984 2.1005 2.1027 2.1048 2.1071 2.1093 2.1117 2.1141 2.1165 2.1190 2.1215 2.1242 2.1268 2.1295 2.1323
%% ローカル関数
function x = func_RK(t, x0)
% 刻み時間Δtの設定
del_t = t(2) - t(1);
% ベクトル t をコピーして, 漸化式で計算する x を作成
x = t;
% 初期値
x(1) = x0;
% 漸化式
for i = 1:(length(t)-1)
% 式(10.16)
dx0 = func(x(i))*del_t;
% 式(10.17)
dx1 = func(x(i)+dx0/2)*del_t;
% 式(10.18)
dx2 = func(x(i)+dx1/2)*del_t;
% 式(10.19)
dx3 = func(x(i)+dx2)*del_t;
% 式(10.20)
x(i+1) = x(i) + (dx0 + 2*dx1 + 2*dx2 + dx3)/6;
end
end
function f = func(x)
A = 2; B = 1;
% f(x) = dx/dt
f = -A*x + B*x^2;
end
拓
le 24 Juin 2023
返信ありがとうございます。原因が分からないのでインストールし直してみます.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur プログラミング dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

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

Start Hunting!