sodiumnitrate
sodiumnitrate

Reputation: 3131

Passing one variable of the two variables defined for a function in MATLAB

I have the following function in MATLAB:

f(x,A) = @(x,A) x'*A*x

where A is an n-by-n matrix and x is an n-by-1 vector. Is it possible that I pass only A into the function as an array of reals, and leave x as symbolic? In other words, I don't want to type the elements of A into the f(x) = @(x) ... and want to be able to change the values of A, say within a loop.

Upvotes: 1

Views: 33

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

It can be done as follows:

>> n = 3;
>> x = sym('x', [n 1]); %// define x as a symbolic n-by-1 vector
>> f = @(x,A) x'*A*x; %'// define function f

>> A = [1 2 3; 4 5 6; 7 8 9]; %// define an n-by-n matrix A
>> f(x,A)
ans =
x1*(conj(x1) + 4*conj(x2) + 7*conj(x3)) + x2*(2*conj(x1) + 5*conj(x2) + 8*conj(x3)) + x3*(3*conj(x1) + 6*conj(x2) + 9*conj(x3))

>> A = [5 6 7; 8 9 10; 10 11 12]; %// now try a different n-by-n matrix A
>> f(x,A)
ans =
x1*(5*conj(x1) + 8*conj(x2) + 10*conj(x3)) + x2*(6*conj(x1) + 9*conj(x2) + 11*conj(x3)) + x3*(7*conj(x1) + 10*conj(x2) + 12*conj(x3))

Upvotes: 2

Dan
Dan

Reputation: 45741

I don't now if I've fully understood you, but what about redefining f at each loop iteration?

X = [1 2 1 3 1];

for t = 1:5
    A = rand(5);
    f = @(x)(x'*A*x);
    disp(f(X));
end

Upvotes: 1

Related Questions