Runge Kutta Loop and save array of results to workspace
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Komal Rajana
le 8 Juil 2020
Commenté : Komal Rajana
le 8 Juil 2020
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
0 commentaires
Réponse acceptée
Alan Stevens
le 8 Juil 2020
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!