MATLAB Answers

Putting multiple equations into a function

53 views (last 30 days)
Hey guys
I have four 1st order odes that I want to put into a function that will be later used with ode45. u1 = x1; u2 = dx1; u3 = x2; u4 = dx2
The equations go as following (These equations come from a two 2nd order odes):
du1 = dx1 = u2
du2 = d2x1 = -k1*(x1 - L1)/m1 + k2*(x2 - x1 - w1 - L2)/m1
du3 = dx2 = u4
du4 = d2x2 = -k2(x2 - x1 - w1 - L2)/m2
Where - L1 = L2 = 2; k1 = k2 = 5; m1 = m2 = 2; w1 = 5
The IC are - x1 = 2; x2 = L1 + w1 + L2 + 6
I have tried everything that I can think of but I have been getting the same error time after time and it is becoming very frustrating. Help would be greatly appreciated

  0 Comments

Sign in to comment.

Accepted Answer

Zoltán Csáti
Zoltán Csáti on 24 Oct 2014
Create this function:
function du = diffeq(t,u)
k1 = 5; k2 = 5;
m1 = 2, m2 = 2; w1 = 5;
L1 = -2; L2 = 2;
du = zeros(4,1);
du(1) = u(2);
du(2) = -k1/m1*(u(1)-L1) + k2/m1*(u(3)-u(1)-w1-L2);
du(3) = u(4);
du(4) = -k2/m2*(u(3)-u(1)-w1-L2);
end
Then invoke it with the appropriate solver (e.g. ode45):
L1 = -2; L2 = 2; w1 = 5;
[t u] = ode45(@diffeq, [0 10], [-2 0 L1+L2+w1+6 0]);
However note that you provided only 2 initial conditions instead of 4. Therefore I supposed the coordinate velocities to be zeroes.

  2 Comments

tyler brecht
tyler brecht on 24 Oct 2014
Thank you so very much! :). I could jump for joy, this work and yes the initial values for velocity are zero forgot to state it in my question. Thank you again
Zoltán Csáti
Zoltán Csáti on 24 Oct 2014
Here, you can find a large amount of materials about the built-in solvers and also how to write a higher order differential equation into a system of first order equations: http://www.mathworks.com/help/matlab/math/ordinary-differential-equations.html

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!