2
votes

I am defining a symbolic function

syms x(n);
x(n) = (n==0);
n=-1:1;

When I try x(n)+x(n-1) I get

 [ -1 == 0, 0 == 0, 1 == 0]
+[ -2 == 0, -1 == 0, 0 == 0]
=[ -3 == 0, -1 == 0, 1 == 0]

I want to force the symbolic function to substitute the values so I get the following results instead.

 [ 0, 1, 0]
+[ 0, 0, 1]
=[ 0, 1, 1]

I tried something like x(n) = logical(n==0); and x(n) = double(n==0); but I got the same result. I know that double(x(n))+double(x(n-1)) works, but I want to use x(n) directly and do the substitution in the definition of the symbolic function. Can this be done?

2
It appears that Mupad will refuse to add booleans, even if you try to force it: evalin(symengine,'TRUE+TRUE') throws Error. - drhagen

2 Answers

2
votes

I think piecewise is the only way to cast a boolean to an integer in Mupad. Unfortunately, it only available in Mupad itself, so you have to use evalin to get it:

syms asinteger(fun) x(n)
asinteger(fun) = evalin(symengine,'piecewise([fun,1],[Otherwise,0])');
x(n) = asinteger(n==0);
n=-1:1;

>> x(n)+x(n-1)

ans =

[ 0, 1, 1]

Think of the asinteger function as the symbolic version of double or int64.

0
votes

I think the easiest way to do is to use isAlways, which evaluates if an expression (equality or inequality) is true:

syms x(n);
x(n) = (n==0);
m = -1:1; % Use a different variable to not overwrite symbolic n
isAlways(x(m))+isAlways(x(m-1))

Or you can use an anonymous function to avoid multiple calls to isAlways:

m = -1:1;
x = @(n)isAlways(sym(n)==0);
x(m)+x(m-1)

Both of these return an array of doubles ([0 1 1]). You can use logical to convert this to a logical array. You might also find sym/isequaln useful in some cases.