Hi I'm new to matlab and I'm trying to run this code for Runge Kutta but I get an error at line 14.

8 vues (au cours des 30 derniers jours)
function rk4_systems_trial()
alpha = [1 -1 2];
m = size(alpha,1);
if m == 1
alpha = alpha';
end
h = 0.02; %the step size
x(1) = 1; %initial conditions
w(:,1) = alpha; %col 1 of matrix w
for i = 1:4 %i=1,2,3,4
k1 = h*f(x(i), w(:,i));
k2 = h*f(x(i)+h/2, w(:,i)+0.5*k1);
k3 = h*f(x(i)+h/2, w(:,i)+0.5*k2);
k4 = h*f(x(i)+h, w(:,i)+k3);
w(:,i+1) = w(:,i) + (k1 + 2*k2 + 2*k3 + k4)/6;
x(i+1) = 1 + i*h;
end
[x' w']
function dy = f(x, y)
dy = [y(2);
y(3);
y(1)*(x+1)^2 +y(2)*(x+1) + y(3)*6 + cos(ln(x+1))];

Réponses (1)

Walter Roberson
Walter Roberson le 4 Mai 2016
MATLAB uses log rather than ln
In your lines
dy = [y(2);
y(3);
y(1)*(x+1)^2 +y(2)*(x+1) + y(3)*6 + cos(ln(x+1))];
the space between the ^2 and the +y(2) is being interpreted as if you have two adjacent array elements, sort of like if you had written
dy = [1;
2;
3 4]
This would not happen if you used a space after the "+",
dy = [y(2);
y(3);
y(1)*(x+1)^2 + y(2)*(x+1) + y(3)*6 + cos(log(x+1))];
Inside [], when there is a space followed by a "+" or a "-" that is not followed by a space, and the whole is not inside (), then the space is interpreted as indicating a new element, and the "+" or "-" are taken as "unary plus" or "unary minus". It is the difference between
[3 +4] or [3 -4]
and
[3 + 4] or [3 - 4] or [3+4] or [3-4]

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by