How to do bit-wise operations on symbolic variables that may be very long possibly larger than inter 64
Show older comments
Below is something I was able to do with some smaller numbers in base 2 and I can do base 10 also. Using Min,Max I can do AND and OR but I haven't been able to understand the use of the Symbolic Tool Box to do this symbolically .
a=12345
b=9867
c=0
n=0
while a>0 |b>0
digita=mod(a,2)
digitb=mod(b,2)
c=c+max(digita,digitb)*2^n
n=n+1
a=floor(a/2)
b=floor(b/2)
end
c
Accepted Answer
More Answers (2)
Walter Roberson
on 27 Jan 2024
Edited: Walter Roberson
on 28 Jan 2024
a = sym(12345);
b = sym(9867);
c = sym(0);
n = sym(0);
while a>0 |b>0
digita=mod(a,2);
digitb=mod(b,2);
c=c+max(digita,digitb)*2^n;
n=n+1;
a=floor(a/2);
b=floor(b/2);
end
c
n
Is this what you are trying to get:
syms a b c n % Create symbols
a = 12345;
b = 9867;
c = sym(0);
n = 0;
while a > 0 || b > 0
digita = mod(a, 2);
digitb = mod(b, 2);
c = c + max(digita, digitb) * 2^n;
n = n + 1;
a = floor(a / 2);
b = floor(b / 2);
end
disp(c);
6 Comments
Walter Roberson
on 27 Jan 2024
syms a b c n % Create symbols
a = 12345;
b = 9867;
c = sym(0);
n = 0;
Assigning double precision values to a and b and n effectively undoes the "syms a b n". Assigning symbolic 0 to c overrides the syms c with a different sym. The "syms a b c n" statement has no effect on the outcome.
Steve
on 27 Jan 2024
Steve
on 27 Jan 2024
John D'Errico
on 27 Jan 2024
@Steve - no. you asked the question. Your question is clear. Don't keep on posting it.
Um, predefining those variables as syms does NOTHING.
syms a b c n % Create symbols
a = 12345;
b = 9867;
whos a b
Do you see that now, a and b are DOUBLES?
Yes, I overlooked. This is what it should be like:
a = sym(12345);
b = sym(9867);
c = sym(0);
n = sym(0);
while a > 0 || b > 0
digita = mod(a, 2);
digitb = mod(b, 2);
c = c + max(digita, digitb) * 2^n;
n = n + 1;
a = floor(a / 2);
b = floor(b / 2);
end
disp(c);
whos a b c n
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!