Getting Both Symbolic Output and Numeric Output

2 views (last 30 days)
I would like to generate symbolic expressions representing the computations involved in a snippet of code (shown below), while simultaneously computing the actual numeric values used to solve the problem.
Let's say A is a 2x2 matrix, B is a 1x2 vector, Q is a 2x2 matrix, and R is a 1x1:
b = 100;
m = 1500;
A = [0 1; 0 -b/m];
B = [0 1/m]';
Q = 2*eye(length(A));
R = 2*eye(size(B,2));
I would like both the numeric solution for K, and the symoblic expressions representing the solution to K. For example,
K = [0 , -0.0125] and
K = [- A11*((B11*Q11)/(R11 + B11*(B11*Q11 + B21*Q21) + B21*(B11*Q12 + B21*Q22)) ...., - A12*((B11*Q11)/(R11 + B11*(B11*Q11 + B21*Q21) + B21*(B11*Q12 + B21*Q22)) ...]
function [ K ] = dlqr_finite( A, B, Q, R, N )
P = cell(1, N);
K = cell(1, N);
P{N+1} = Q;
% Solve backwards in time from N to 0
n = N+1;
while n > 1
P{n-1} = Q + (A.'*P{n}*A) - (A.'*P{n}*B)*(R+B.'*P{n}*B)^-1*(B.'*P{n}*A);
K{n-1} = -1*(R+B.'*P{n}*B)^-1*(B.'*P{n}*A);
n = n-1;
end
end
What is the easiest way to achieve these simultaneously?

Accepted Answer

Karan Gill
Karan Gill on 21 Nov 2016
Calculate the answer symbolically and substitute values in at the end.
Start with symbolic matrices and variables ...
syms b m
A = sym('A%d%d',[2 2])
B = sym('B%d%d',[2 1])
Q = sym('Q%d%d',[2 2])
syms R
Find K. Then define your numeric values.
bVal = 100;
mVal = 1500;
Aval = [0 1; 0 -bVal/mVal]
...
Now substitute to get your numeric answer.
KVal = subs(K,A,Aval);
KVal = subs(K,B,Bval);
...
Finally, use 'vpa' or 'double' to convert to floating point.
  2 Comments
Jonathan
Jonathan on 21 Nov 2016
Awesome! Thanks for pointing out the 'subs' function.
Karan Gill
Karan Gill on 22 Nov 2016
Happy to help! In general the workflow is to stay symbolic as far as possible and then substitute in numeric values when it becomes necessary. It's hard to communicate this well in the doc without making every example about 'subs'.

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!