System of Differential Equations- How can I avoid an index error when my first equations depend on second derivatives of later equations?

I am solving a basic system of differential equations. I have the following simple function:
function dy = waspstandardq(t,y)
dy = zeros(2,1);
C1 = 5;
f = 1;
C3 = 15;
C2 = 90;
C4 = 35;
Vo = 2;
R3 = 5;
M = 20;
M2 = 20;
L1 = 20;
L3 = 20;
R4 = 10;
L2 = 20;
L4 = 20;
R1 = 5;
R2 = 5;
G = sin(1.5*t)*2.7^(-t);
y(1) = y(2);
% CS
dy(2) = (dy(4)*M +dy(6)*M - (y(1)/C2) - (R3*y(2)) /(2 * L3));
dy(3) = y(4);
% WF
dy(4) = ((dy(2)*M - (y(3)/C1) - (R1* y(4)) +Vo-G)/(L2));
dy(5) = y(6);
% PF
dy(6) =((dy(4)*M+(dy(8))*M2 - (y(5)/C3) - (R2*y(6))) /(2*L1));
dy(7) = y(8);
% B
dy(8) = ((dy(6)*M2) - (y(7)/C4) - (R4*y(8)) )/(L4);
Then I run it with this:
[t,y] = ode45('waspstandardq',[0 1000], [0 0 0 0 0 0 0 0 ]);
It works of course if the equations don't depend upon the second derivative terms. How can I avoid the error when MATLAB reads dy(4) for instance, before it is defined? Obviously I can not define it sooner.

4 Comments

I don't exactly undertsand your code, but it looks like the problem is that you're initializing dy to be a 2x1 matrix when you need at least a 8x1 matrix. Try changing the line to be dy = zeros(8,1);
I could help if you have a PDF of the symbolic version of your equations that we could read. We really don’t know the system you’re integrating.
The derivatives themselves should be on the LHS only, and form a column vector.
Well that was silly- Thank you very much; it works fine now:)
Just out of curiosity, what did the problem turn out to be, and what solved it?

Answers (0)

This question is closed.

Asked:

on 19 Dec 2015

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!