符号运算和求和不能得到正确答案

Symbolic comprision operation and summation cant get right answer

我对 MATLAB 的符号运算优先级感到困惑。我的代码没有产生所需的输出。

syms x1 x2 x3 x4
aa=((x1 == 0 & x2 == 0 & x3 == 0 & x4 == 0) + ((9*x1)/50 + (327*x2)/2000 + (1841*x3)/20000 + (1799*x4)/20000));
bb=eval(subs(aa, [x1 x2 x3 x4], [0.2 0.2 0.2 0.2]))

我期待

的输出
bb=
    0.1051

但实际输出是

bb =
    logical
    0

MATLAB 为什么要这样做? 我使用 MATLAB R2018b

我认为 MATLAB 试图减少生成最简单输出所需的括号数量。注意如果a等于ba+c也等于b+c,所以这个说法没有错。如果你调用 simplify(aa) 你甚至会得到一个简单的 a == b,这确实是最简单的形式,因为可以取消两边的 c

syms a b c
aa=(a==b)+c
aa =
a + c == b + c
pretty(aa)
a + c == b + c

simplify(aa)
ans =
a == b

关于您编辑过的问题:您为什么要使用符号变量?它们缓慢而笨重(更不用说 )。使用数值计算 会产生正确的结果:

syms x1 x2 x3 x4
aa=((x1 == 0 & x2 == 0 & x3 == 0 & x4 == 0) + ((9*x1)/50 + (327*x2)/2000 + (1841*x3)/20000 + (1799*x4)/20000));
bb=eval(subs(aa, [x1 x2 x3 x4], [0.2 0.2 0.2 0.2]))
bb =
  logical
   0

x1=0.2;x2=0.2;x3=0.2;x4=0.2;
(x1 == 0 & x2 == 0 & x3 == 0 & x4 == 0)
ans =
  logical
   0

((9*x1)/50 + (327*x2)/2000 + (1841*x3)/20000 + (1799*x4)/20000)
ans =
    0.1051

aa=((x1 == 0 & x2 == 0 & x3 == 0 & x4 == 0) + ((9*x1)/50 + (327*x2)/2000 + (1841*x3)/20000 + (1799*x4)/20000))
aa =
    0.1051

我怀疑问题出在 subs and/or eval.

的肚子里
  • 案例一: x == y
syms x y z

aa = (x == y) + z

意思

aa = [x or y] + z = x + z = y + z

Wherever you have x, you can replace it by y, interchangeably.
It does not check if x and y are the same


  • 案例二: isequal(x, y)
syms x y z

aa = (x == y) + z
aa = isequal(x, y) + z

意思

aa = [check if x and y are the same] + z = 0 + z = z

使用 isequal()

修改给定的代码
syms x1 x2 x3 x4
aa=((isequal(x1, 0)& isequal(x2, 0) & isequal(x3, 0) & isequal(x4, 0)) + ...
    ((9*x1)/50 + (327*x2)/2000 + (1841*x3)/20000 + (1799*x4)/20000));
bb=eval(subs(aa, [x1 x2 x3 x4], [0.2 0.2 0.2 0.2]));

结果

bb = 0.1051