Why it is always error?

2 views (last 30 days)
Lan
Lan on 12 Mar 2015
Commented: Lan on 13 Mar 2015
Why it is always error? Anybody can help me? Thank you!
MatlabM.file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%function dx=myfun(t,x)
syms a e f g a1 a2 e1 e2 f1 f2 g1 g2
dx = zeros(5,1);
dx(1)=x(3)-x(2)+x(4)*x(2)-2*x(5)*x(2)-x(2)*x(2)-x(5)-e-f-g; dx(2)=x(1)-x(3)+x(4)*x(2)-x(2)*x(2)-x(5)*x(5)-x(5)*x(2)-e*f-g; dx(3)=x(2)-x(1)+x(5)*x(1)-x(4)*x(3)+x(3)+x(4)+e*g+f; dx(4)=x(5)*a+x(3)*x(1)+x(3)+e*f*g*x(6); dx(5)=x(4)*a+x(2)*x(1)-e*f*x(1)-x(2)*x(2)*x(5)-x(2)*x(5)*x(5)-e*f-f*g;
a=a1+a2; e=e1+e2; f=f1+f2; g=g1+g2;
a1=1; a2=1; e1=9; e2=7; f1=56; f2=98; g1=76; g2=665;
dx=dx(:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Matlab: clear all clc
x0=[1,1,1,1,1,1]; t0=0:0.1:2; [t,x]=ode45('myfun',[0,10],x0); %?%ode45会自动调整步长 plot(t,x) % ? legend('x(1)','x(2)','x(3)','x(4)','x(5)','x(6)')

Answers (1)

Stephen23
Stephen23 on 13 Mar 2015
Edited: Stephen23 on 13 Mar 2015
What you are doing makes no sense: you define some values as symbolic, and then try to use them in a numeric solver ode45. You need to decide what you are doing: are you working with symbolic mathematics or numeric mathematics?
Who told you to use syms? Why do you think these declarations are necessary?
And why do you have plot(t,x) and legend('x(1)','x(2)','x(3)','x(4)','x(5)','x(6)') before your ode45 call even works?
You need to learn to write code carefully, checking each line that it works and gives the expected result before moving onto the next. Writing a large amount of untested code all at once, finding that it does not work and then trying to find the bugs is not a good way to program. Learn to test your code as you write it. If you had done this you would have avoided all of the errors in this code.
If you get rid of the syms declarations and defined the values before that calculation, then the numeric function solving might work, although t is not currently used anywhere inside the function:
function dx=myfun(t,x)
a1=1; a2=1; e1=9; e2=7; f1=56; f2=98; g1=76; g2=665;
a=a1+a2; e=e1+e2; f=f1+f2; g=g1+g2;
dx = zeros(5,1);
dx(1)=x(3)-x(2)+x(4)*x(2)-2*x(5)*x(2)-x(2)*x(2)-x(5)-e-f-g; dx(2)=x(1)-x(3)+x(4)*x(2)-x(2)*x(2)-x(5)*x(5)-x(5)*x(2)-e*f-g; dx(3)=x(2)-x(1)+x(5)*x(1)-x(4)*x(3)+x(3)+x(4)+e*g+f; dx(4)=x(5)*a+x(3)*x(1)+x(3)+e*f*g*x(6); dx(5)=x(4)*a+x(2)*x(1)-e*f*x(1)-x(2)*x(2)*x(5)-x(2)*x(5)*x(5)-e*f-f*g;

Community Treasure Hunt

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

Start Hunting!