Runge kutta order 2 by hand

1 回表示 (過去 30 日間)
Dominic Nightingale
Dominic Nightingale 2019 年 12 月 12 日
編集済み: Jim Riggs 2019 年 12 月 12 日
I am trying to runge-kutta order 2 and I keep getting this error
Unable to perform assignment because the left and right sides have a different number of elements.
Error in RungeKutta2 (line 24)
Y(1) = [t(1);y(1)]
Error in prob1 (line 11)
[y] = RungeKutta2(f, n, x1, x2,t0,y0,c2);
% input parameters
f = @(y) 0.5*sin(y(1,:)) + (cos(y(2,:)+y(1,:)))*(atan(y(2,:)) - 0.5*cos(y(2,:)));
n = 10;
x1 = 0;
x2 = 5;
t0 = 0;
y0 = 1;
c2 = 0.5;
%calling RungeKutta2 function
[y] = RungeKutta2(f, n, x1, x2,t0,y0,c2);
%
%the above is in a seperate script file from the function file below.
%
function [y] = RungeKutta(f, n, x1, x2,t0,y0,c2)
% calculate c1,a,b parameters
c1 = 1-c2;
a = 0.5/c2;
b=a;
% calculate step size
h=(x2-x1)/n;
% setting up interval and number of steps
t = linspace(x1,x2,n+1)
% preallocating space for aproximations to be calculated
y = zeros(1,n+1)
% initializing first term in for loop
y(1) = y0;
Y = [t;y]
Y(1) = [t(1);y(1)]
% initializing k1 in for loop
k1 = f(Y)
k1(1) = f(Y(1));
% initializing k2 in for loop
Y2 = [t + a*h; y + h*b*k1];
Y2(1) = [t(1) + a*h; y(1) + h*b*k1(1)];
k2 = f(Y2);
k2(1) = f(Y2(1));
%
% for loop over the number of steps to take with formula given to us in
% class
for ii = 2:length(t)
y(ii) = y(ii-1) + h * (c1*k1(ii-1) +c2*k2(ii-1));
end
end

回答 (1 件)

Jim Riggs
Jim Riggs 2019 年 12 月 12 日
編集済み: Jim Riggs 2019 年 12 月 12 日
In the statement
Y(1) = [t(1);y(1)]
the simi-colon ";" indicates you are attempting to put 2 rows of numbers into a single row of Y.
I'm not sure what yu are trying to do, but changing this to
Y(1:2) = [t(1);y(1)];
or
Y(1,1:2) = [t(1);y(1)];
will concatenate t and y into Y.
The following also will have the same effect:
Y(1) = [t(1):y(1)];

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by