0

考虑脚本

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

这会产生一个向量作为输出 ([0, 4]),但预期的输出是一个标量 (4),因为应该执行逐元素乘法。

替换符号函数时如何正确利用向量?

4

1 回答 1

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
于 2017-04-22T19:45:36.443 回答