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.
7 views (last 30 days)
Show older comments
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))];
1 Comment
CS Researcher
on 4 May 2016
What is the error? Have you defined w somewhere before this? If not, use w = alpha instead.
Answers (1)
Walter Roberson
on 4 May 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]
0 Comments
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!