- Preallocate the vector before populating it...
How to solve a system of coupled first order differential equations using ode45?
5 views (last 30 days)
Show older comments
Commented: Md. Golam Zakaria on 1 Feb 2023
I have a system of four coupled first oder differential equation, which needs to be solved. While the equations are long, its pretty straightforward. I have written the following code and getting some error.
v_e = 594.0413;
To call this function I used [t,y]=ode45('ccp_ode', [0 .1], [0 0 2 0]). However I am getting the following error:
Error using odearguments (line 93)
CCP_ODE must return a column vector.
Can anyone please , point me the problem with my code and what is the solution.
dpb on 1 Feb 2023
The error message tells you what the problem is -- the above will return a row vector because you didn't preallocate the variable nor expressly define the terms as column vector members nor reshape() the result to ensure the function returns a column vector.
You could have found this easily by just using the debugger to inpsect the result in your function before it returns or looking at what it returned if called from the command line standalone.
To solve it is simple; several ways...
2. Explicitly store into first column...
3. Ensure result is column vector...
Of these, the cleanest is the first as it avoids the dynamic reallocation that occurs with any of the others without having done so. For only four elements the performance difference will be negligible except the function will be called every solution pass and multiple times for evaluation for every time step so performance here may well be significant. Hence, get into the habit of preallocating arrays where can.
More Answers (0)
Find more on Numerical Integration and Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!