1
votes

I'm trying to solve a system with three differential equations with the function ode45 in Matlab. I do not really understand the errors i am getting and i could use some help understanding what im doing wrong.

The differential equations are the following:

F1 = -k1y1+k2(y2-y1)
F2 = -k2(y2-y1)+k3(y3-y2)
F3 = -k3(y3-y2)

And my code in Matlab is this:

function dz = kopplad(t, z)
global m1 m2 m3 k1 k2 k3 
dz = [z(2)
-k1*z(1)/m1 + k2*(z(2)-z(1))/m1
z(4)
-k2*(z(2)-z(1))+k3(z(3)-z(2))/m2
z(6)
-k3(z(3)-z(2))/m3];

global m1 m2 m3 k1 k2 k3
m1 = 0.75; m2 = 0.40; m3 = 0.65;
k1 = 0.85; k2 = 1.1; k3 = 2.7;
[t, z] = ode45(@kopplad, [0, 50], [0 -1 0 1 0 0]);
plot(t, z(:,1)) 
hold on
plot(t,z(:,3),'--')
plot(t,z(:,5),'*') 
legend('y_1', 'y_2', 'y_3');
hold off

The errors I'm recieving are the following:

Attempted to access k3(1.00002); index must be a positive integer or logical.

Error in kopplad (line 3) dz = [z(2)

Error in ode45 (line 262) f(:,2) = feval(odeFcn,t+hA(1),y+f*hB(:,1),odeArgs{:});

Error in diffekv (line 6) [t, z] = ode45(@kopplad, [0, 50], [0 -1 0 1 0 0]);

1
Can you share the errors you receive? Probably it will help the others to understand what is the reason of your issue.Vadim
Without actually telling us what errors you get, you now force someone else to try executing your code. Make it easy on us and give us a hint! Include the COMPLETE error message. Making it easy on us means it will be faster/easier to give you an answer.user85109
The errors i'm recieving are the following: Attempted to access k3(1.00002); index must be a positive integer or logical. Error in kopplad (line 3) dz = [z(2) Error in ode45 (line 262) f(:,2) = feval(odeFcn,t+hA(1),y+f*hB(:,1),odeArgs{:}); Error in diffekv (line 6) [t, z] = ode45(@kopplad, [0, 50], [0 -1 0 1 0 0]);Bobbie
You're actually only getting one error: k3(1.00002). The rest of the messages are there because the function calls are nested (you call ode45, which in turn calls kopplad, which has the error in it). The mistake is simply a * that you forgot after k3 in your declaration of dz.Etienne Pellegrini

1 Answers

0
votes

A while passed since I did some Matlab programming, but as far as I remember, you should pass variables to the function, i.e. write @(x,y)kopplad(x,y), if I understand you code in a correct way. If the rest (global variables and equations) are correct, everything shall be fine.