Error in naming function handles

1 view (last 30 days)
Xingda Chen
Xingda Chen on 8 Mar 2020
Commented: Walter Roberson on 8 Mar 2020
Hi all,
I am writting a Runge Kutta for a time varying system of ODEs, but bumped into an error of indexing. I think the problem comes from how I type the function handle but i have no idea how to fix it.
Any clue?
here is the error:
Error using sym/subsasgn (line 961)
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be
symbolic variables, and function body must be sym expression.
and here is my code:
%define function handles
fx1= @(t, x1, x2) ((-t)/(1+t^2))*x1 + x2
fx2 = @(t, x1, x2) (((-4)*t)/(1+t^2))*x2
%deine initial condition
t(1) = 0
x1(1) = 0;
x2(1) = 1;
%define step size
h = 0.1
tfinal= 5
N= ceil(tfinal/h)
%make a loop
for i = 1:N
t(i+1)= t(i)+h; %time update
k1x1= fx1(t(i), x1(i), x2(i));
k1x2= fx2(t(i), x1(i), x2(i));
k2x1= fx1(t(i)+h/2, x1(i)+h/2*k1x1, x2(i)+h/2*k1x2);
k2x2= fx2(t(i)+h/2, x1(i)+h/2*k1x1, x2(i)+h/2*k1x2);
k3x1= fx1(t(i)+h/2, x1(i)+h/2*k2x1, x2(i)+h/2*k2x2);
k3x2= fx2(t(i)+h/2, x1(i)+h/2*k2x1, x2(i)+h/2*k2x2);
k4x1= fx1(t(i)+h, x1(i)+h*k3x1, x2(i)*k3x2);
k4x2= fx2(t(i)+h, x1(i)+h*k3x1, x2(i)*k3x2);
%updating the function
x1(i+1) = x1(i) + (h/6)* (k1x1 + 2*k2x1 + 2*k3x1 + k4x1);
x2(i+1) = x2(i) + (h/6)* (k1x2 + 2*k2x2 + 2*k3x2 + k4x2);
%plotting the solution
hold on

Answers (1)

David Hill
David Hill on 8 Mar 2020
Code works just fine as stand alone. Did you previously use/assign any of your variables (t,x1,x2) as symbolic? I could not find anything wrong with your code and I pasted into matlab and ran it without error.
k2x1= fx1(t(i)+h/2, x1(i)+h/2*k1x1, x2(i)+h/2*k1x2);%Do you mean h/2/k1x2 or what you have? I would normally write h*k1x2/2 or add () to be less confusing.
Walter Roberson
Walter Roberson on 8 Mar 2020
That code could have problems if t, x1, or x2 were defined before the code ran, including if they were defined as symbolic. You should be using
t = zeros(1, N+1);
x1 = zeros(1, N+1);
x2 = zeros(1, N+1);

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by