Eivind
Eivind

Reputation: 301

Substitute symbolic variables with vectors

Consider the script

syms a b;
f = a.*b;
a = [1 2];
b = [0 2];
subs(f)

This yields a vector as output ([0, 4]), but the intended output is a scalar (4), given the element-wise multiplication that should be performed.

How can I properly utilize vectors when substituting symbolic functions?

Upvotes: 0

Views: 432

Answers (1)

I believe you're making two mistakes. The first is that you're overwriting your symbolic variables with double arrays, so you're not actually calling subs for a symbolic object:

>> syms a;   
>> class(a)

ans =

sym

>> a = [1 2];
>> class(a)

ans =

double

The second is that preventing this will still give a wrong answer:

>> syms a b;
>> f = a.*b

f =

a*b

>> subs(f,{a,b},{[1, 2], [0,2]})

ans =

     0     4

That's because, as you see in the printed version of f, the symbolic engine treats a and b as scalars.

So to do what you probably want to do you need to define your syms to be 2-element arrays:

> a = sym('a',[1 2])

a =

[ a1, a2]

>> b = sym('b',[1 2])

b =

[ b1, b2]

>> f = a.*b

f =

[ a1*b1, a2*b2]

>> subs(f,[a,b],[[1,2],[0,2]])       

ans =

     0     4

But anyway, as you can see, the result is still an array since .* (or symbolic *) is elementwise multiplication. In order to get a scalar product, use sym/dot:

>> dot(a,b)                    

ans =

b1*conj(a1) + b2*conj(a2)

>> subs(dot(a,b),[a,b],[[1,2],[0,2]])

ans =

     4

Upvotes: 1

Related Questions