MATLAB: Anonymous function surface plot

anonymous functionplotquadratic form

Im creating a quadratic form function. Its defined as anonymous function of n-dimensional vector. But when I try to plot it I get an error saying that Z (in surface plot) must be matrix and not a vector. I have n set to 2 but it wont let me plot it. Is there a way to choose have many inputs my anonymous function has?
n = 2;
x_opt = randi([-6,6],n,1);
A = randi(n,n);
T = A*A' + eye(n,n);
h = -T*x_opt;
Q = @(x) 1/2*x'*T*x + h'*x; % n dimensional vector as input
[X,Y] = meshgrid(linspace(-10,10,100));
surf(X,Y,Q,'Edge Color','None') % only 2 dimensional input

Best Answer

Are you looking for something like this?
n = 2;
x_opt = randi([-6,6],n,1);
A = randi(n,n);
T = A*A' + eye(n,n);
h = -T*x_opt;
Q = @(x) 1/2*x'*T*x + h'*x; % n dimensional vector as input
[X,Y] = meshgrid(linspace(-10,10,100));
Qvals = zeros(size(X));
for i=1:100
for j= 1:100
Qvals(i,j) = Q([X(i,j);Y(i,j)]);
end
end
surf(X,Y,Qvals,'EdgeColor','None') % only 2 dimensional input
Related Question