aliceW
aliceW

Reputation: 3

Symbolic comprision operation and summation cant get right answer

I'm confused about MATLAB's symbolic operation precedence. My code does not produce the desired output.

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]))

I expect the output of

bb=
    0.1051

but the actual output is

bb =
    logical
    0

Why does MATLAB do this? I use MATLAB R2018b

Upvotes: 0

Views: 61

Answers (2)

Adam
Adam

Reputation: 2777

  • Case 1: x == y
syms x y z

aa = (x == y) + z

Meaning

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


  • Case 2: isequal(x, y)
syms x y z

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

Meaning

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

Modify the given code to this using 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]));

Result

bb = 0.1051

Upvotes: 2

Adriaan
Adriaan

Reputation: 18177

I think MATLAB tries to reduce the number of brackets necessary to produce the simplest output. Note that if a is equal to b, a+c is also equal to b+c, so the statement is not wrong. If you call simplify(aa) you even get a simple a == b, which is indeed the simplest form as one can cancel the c on both sides:

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

simplify(aa)
ans =
a == b

With respect to your edited question: why are you using symbolic variables at all? They are slow and cumbersome (not to speak about the unspeakable evil that is eval). Using numeric computation does yield the correct result:

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

I suspect the problem is somewhere in the belly of subs and/or eval.

Upvotes: 1

Related Questions