Runge Kutta Loop and save array of results to workspace

조회 수: 8 (최근 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 CenterFile Exchange에서 App Building에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by