How can I solve a matrix differential equation within MATLAB?
6 views (last 30 days)
Show older comments
I am interested in solving an ODE dF/dt=F*A, where both A and F are matrices (in particular, 5x5 matrices). I have used ode45 and dsolve before for problems like dx/dt=A*x, where x is a vector but not a matrix like in this case.
EDIT:
I am using now a version of your example code with my 5x5 matrix A which is complex and defined as an anonymous function. Seems to work fine, is there any implemented method in MATLAB to check the solutions given by ode45? Thank you.
0 Comments
Accepted Answer
James Tursa
on 21 Mar 2017
Edited: James Tursa
on 23 Mar 2017
E.g., if you are using ode45, then simply reshape F and the initial Fo into column vectors. Inside the derivative routine, reshape the input argument F into a matrix, do your F*A matrix multiply, then reshape the multiply result back into a column vector for output.
EDIT:
Here is a small example showing the technique
function matrix_deriv_example
A = rand(2,2); % Some arbitrary matrix we will use
F0 = eye(2); % Some arbitrary matrix initial value
odefun = @(t,y) deriv(t,y,A); % Anonymous derivative function with A
tspan = [0 5];
[T,F] = ode45(odefun,tspan,F0(:)); % Pass in column vector initial value
F = reshape(F.',2,2,[]); % Reshape the output as a sequence of 2x2 matrices
n = size(F,3);
e = zeros(2,n);
for k=1:n
e(:,k) = eig(F(:,:,k)); % Calculate the eigenvalues of the 2x2 matrices
end
plot(T,e(1,:),T,e(2,:)); grid on % Plot them
xlabel('Time')
ylabel('Eigenvalues')
end
function dy = deriv(t,y,A)
F = reshape(y,size(A)); % Reshape input y into matrix
FA = F*A; % Do the matrix multiply
dy = FA(:); % Reshape output as a column vector
end
More Answers (0)
See Also
Categories
Find more on Ordinary 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!