Generate function handle for odesolver dynamically

Hello,
for a course we should simulate a motorcade where each driver chooses his speed depending on the driver in front of him. The difficulty is that the number of cars should be changed dynamically, which makes it hard to define the function handle for the odesolver.
I already tried some options:
Overwriting the existing equation with the next car attached:
equation = @(t,y) [y(2); 20-y(2)]; %differential eqaution for first car
equation = @(t,y) [equation(t,y); y(4); equationForAcceleration] %adding the second car
This doesn't work because it doesn't copy the first eqaution, just references to it.
Wiritng the equations into a cell and then converting it:
equation{1} = @(t,y) y(2); %speed of first car
equation{2} = @(t,y) 20-y(2); %acceleration of first car
equation{3} = @(t,y) y(4); %speed of second car
equation{4} = @(t,y) equationForAcceleration; %acceleration of second car
eq = cell2mat(equation);
This results in: Error using cat Nonscalar arrays of function handles are not allowed; use cell arrays instead.
I also tried str2func but this only works with scalar strings.
How can I make this work? Except integrating for the first car, using the solution of the first car to integrate the second car and so on and so forth... Or is this the only option anyways?
Thanks

2 Comments

Depending on what will it be necessary to change the number of cars under consideration (the number of equations to be solved) ? Will this happen during the integration process ?
We are fairly free in how we implement the problem.
My vision is that in the beginning of the program I define a constant number_of_cars and then just run the program. So the number of cars remains constant for the whole execution, we just want an easy way to change the number of cars for another run of the simulation.

Sign in to comment.

 Accepted Answer

Define your equations by a function instead of a function handle. In the function, you can make a loop in order to account for the actual number of cars.
Example:
function dy = equations(t,y,number_of_cars)
for i = 1:number_of_cars
dy(2*i-1) = y(2*i);
dy(2*i) = 20 - y(2*i);
end
end

1 Comment

This works, thanks, I jsut had to define
dy = zeros(2*number_of_cars,1);
before setting the equations.

Sign in to comment.

More Answers (0)

Products

Release

R2022b

Community Treasure Hunt

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

Start Hunting!