Error in naming function handles
1 回表示 (過去 30 日間)
古いコメントを表示
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?
Thanks!
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);
end
%plotting the solution
plot(t,x1)
hold on
plot(t,x2)
xlabel('time')
ylabel('values')
legend('x1','x2')
0 件のコメント
回答 (1 件)
David Hill
2020 年 3 月 8 日
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.
4 件のコメント
Walter Roberson
2020 年 3 月 8 日
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);
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!