FFT
FFT

Reputation: 969

Matlab numeric evaluation of vector function

I am trying to evaluate a symbolic vector function by plugging in numeric values. After initializing the symbolic vectors, I get values XX1, XX2, XX3, etc...However, when I try to plug in numeric vectors, I get the error: undefined function or variable. Any help would be appreciated. Thanks!

syms yy
XX = sym('XX', [1 3]);
ww = sym('ww', [1 3]);
f = log(0.5)+log(1+((2*yy-1)*dot(XX,ww))/sqrt(1+dot(XX,ww)^2));
gf = gradient(f,ww);
hf = hessian(f,ww);
%create numeric vectors
X = rand(3,1);
w = rand(3,1);
y = 1;
for (m = 1:length(w))
    XX(m) = X(1,m);
    ww(m) = w(m);
end
yy = y;
eval(gf);
eval(hf);

Upvotes: 0

Views: 179

Answers (2)

TroyHaskin
TroyHaskin

Reputation: 8401

The error stems from the fact that while you do assign values to the symbolic variables XX and ww, you don't assign values to the symbolic variables they held. For example, the variable XX initial value is

XX =
[ XX1, XX2, XX3]

and after your rand(1,3) assignment, it has the symbolic components replace with numbers

XX =
0.7317    0.6477    0.4509

But the values of XX1, XX2, and XX3 are still undefined. You can define those values one-by-one and use eval but don't.

You should either do as @David suggested and make a MATLAB function handle from the output or use subs if you only need to do this once:

X = rand(1,3);
w = rand(1,3);
y = 1;
value = subs(gf,[XX,ww,yy],[X,w,y]);

Upvotes: 1

David
David

Reputation: 8459

Use matlabFunction to convert from symbolic functions to numerical functions

syms yy
XX = sym('XX', [1 3]);
ww = sym('ww', [1 3]);
f = log(0.5)+log(1+((2*yy-1)*dot(XX,ww))/sqrt(1+dot(XX,ww)^2));
gf = gradient(f,ww);
hf = hessian(f,ww);
%create numeric vectors
X = rand(1,3); %// Note your XX and ww were 1x3 so X and w should be as well
w = rand(1,3);
y = 1;

hfNumerical=matlabFunction(hf,'Vars',{XX,ww,yy})
hfNumerical(X,w,y)

gfNumerical=matlabFunction(gf,'Vars',{XX,ww,yy})
gfNumerical(X,w,y)

You have to specify the variables like this so that they stay as vector/matrix inputs.

Upvotes: 1

Related Questions