MATLAB: How to avoid symbolic matrix inverse in optimization

Optimization Toolboxsymbolic matrixunnecessarily symbolic

I am using fminunc to find the minimum of an element of matrix B, B(11,11).
Matrix B is a function of Matrix A with elememts of variables, B=pinv(I+A * Z)*(I-A * Z), where I and Z is known matrix. A is a 21*21 symbolic matrix with variable x1 and x2.
Problem: if I denote A using symbols x1 and x2, then the symbolic expression of B is super difficult to obtain becasue of the inverse calculation. I think if there is no symbolic matrix calculation, then it should be faster. how to solve it?
clc
clear
x = sym('x',[1,2]);
Z = diag(rand(1,21));
I = eye(21);
syms x1 x2
A = [x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;...
x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;...
0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;...
0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;...
0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;...
0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0,0;...
0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0,0;...
0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0,0;...
0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0,0;...
0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0,0;...
0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0,0;...
0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0,0;...
0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0,0;...
0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0,0;...
0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0,0;...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0,0;...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0,0;...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0,0;...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2,0;...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1,x2;...
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x2,x1;...
];
B = pinv(I+A * Z)*(I-A * Z);
funx = B(11,11);
fun = matlabFunction(funx,'Vars',{x});
x0 = [1,1];
[x,fval] = fminunc(fun,x0)

Best Answer

Can't you just skip all of the symbolic stuff?
function out=fun(x,I,Z)
A=toeplitz([x(:).',zeros(1,19)]);
B = pinv(I+A * Z)*(I-A * Z);
out=B(11,11);
end
x0 = [1,1];
[x,fval] = fminunc(@(x) fun(x,I,Z),x0)