Runge Kutta Loop and save array of results to workspace

7 ビュー (過去 30 日間)
Komal Rajana
Komal Rajana 2020 年 7 月 8 日
コメント済み: Komal Rajana 2020 年 7 月 8 日
Hello,
I would like to run the runge kutta method within a loop for various values for 'p'. My problem is saving the array of results (for outputs=Y) in the workspace for each loop/increment of 'p'. Please assist. Thank you
function [x, y] = FunctionBeta_Executor(F)
for p=1:0.2:5
h=0.15; % step size (smaller step size gives more accurate solutions)
x = 0:h:3; % x space
y = zeros(length(x):1); % Memory allocation
y(1) = 0; % initial condition
F = @(x, y)(x+y+p);
for i=1:(length(x)-1)
% i=1:(length(x)-1) % calculation loop
k1 = F(x(i),y(i));
k2 = F(x(i)+0.5*h,y(i)+0.5*h*k1);
k3 = F((x(i)+0.5*h),(y(i)+0.5*h*k2));
k4 = F((x(i)+h),(y(i)+k3*h));
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h; % main equation
end
figure, plot(x, y) % To see the solution results
end
end

採用された回答

Alan Stevens
Alan Stevens 2020 年 7 月 8 日
Here's one way:
p=1:0.2:5;
h=0.15;
x = 0:h:3;
y = zeros(length(x),length(p));
F = @(x, y, p)(x+y+p);
for j=1:length(p)
y(1,j) = 0; % initial condition
for i=1:(length(x)-1)
k1 = F(x(i),y(i,j), p(j));
k2 = F(x(i)+0.5*h, y(i,j)+0.5*h*k1, p(j));
k3 = F((x(i)+0.5*h), y(i,j)+0.5*h*k2, p(j));
k4 = F((x(i)+h), y(i,j)+k3*h, p(j));
y(i+1,j) = y(i,j) + (1/6)*(k1+2*k2+2*k3+k4)*h; % main equation
end
end
figure, plot(x, y) % To see the solution results

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeApp Building についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by