Home > database >  Using symbolic variable in boolean algebra with MATLAB
Using symbolic variable in boolean algebra with MATLAB

Time:07-12

How do I substitute the symbolic variables in a boolean expression? I am having this problem and can't solve it even in the example below.

syms a
syms b

o = myand(a, b);

where

function o = myand(a, b)
    o = and(a, b);
end

I also tried the below but got an "Invalid Operand" error.

subs(o, [a, b], [1, 1])

I also tried using the not() function (one input) and it worked. I read MATLAB documentation and I cannot figure out what I am doing wrong.

CodePudding user response:

Ah, so for the and expression from the Symbolic Toolbox in MATLAB, it requires an actual mathematical expression for each operand. The reason why the not operator worked for you is because it is able to take in numbers, vectors, anything that is numeric in addition to symbolic expressions. From the not documentation:

A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic function | symbolic expression

Compared with and:

A - Input
symbolic equations | symbolic inequalities | symbolic expressions | symbolic arrays

So the and function actually does not take in single values when you do substitutions. Also, I suspect that if you just use a and b as is, it doesn't actually understand that if a is not zero, this should be true. The same goes for b. A workaround is to define the function, but condition both variables so that anything greater than 0 is true, else false. This should still hold within the binary universe:

function o = myand(a, b)
    o = and(a > 0, b > 0);
end

For this to be more compact, we can define an anonymous function instead:

myand = @(a, b) and(a > 0, b > 0);

Now if you try it, it should work:

syms a b;
myand = @(a, b) and(a > 0, b > 0);
o = myand(a, b);
c = subs(o, [a, b], [1, 1]);

We get for c:

>> c
 
c =
 
0 < 1

... so yeah, that's technically true. We can convert this into a numeric result:

>> double(c)

ans =

     1
  • Related