how to perform xor of two bits in matab
2 views (last 30 days)
Show older comments
- I am learning matlab on my own and would be helpful if someone provide me knowledge with it.
j = mat2str(dec2bin(randi([0,3],5,16)));
sc_o = mat2str(dec2bin(randi([0,3],5,16)));
I want to perform xor of these two matrix in matlab but I am not sure if I can perform it or not. Can someone please provide suggestions regarding it??
0 Comments
Answers (2)
dpb
on 14 Mar 2019
See
doc bitxor
to do the logical operation on the content of the variable in its internal storage pattern; you can convert the result with dec2bin if you want to see the resulting bit patterns.
>> bxor=bitxor(j,sc_o);
>> reshape(cellstr(dec2bin(bxor)),size(j))
ans =
5×16 cell array
{'11'} {'10'} {'11'} {'10'} {'10'} {'01'} {'11'} {'10'} {'10'} {'01'} {'00'} {'00'} {'01'} {'11'} {'00'} {'01'}
{'00'} {'10'} {'11'} {'00'} {'10'} {'00'} {'01'} {'01'} {'11'} {'01'} {'01'} {'11'} {'01'} {'10'} {'11'} {'00'}
{'11'} {'01'} {'01'} {'11'} {'01'} {'00'} {'00'} {'11'} {'01'} {'01'} {'10'} {'10'} {'01'} {'11'} {'01'} {'10'}
{'01'} {'10'} {'00'} {'11'} {'11'} {'11'} {'10'} {'01'} {'11'} {'01'} {'00'} {'10'} {'00'} {'11'} {'00'} {'01'}
{'11'} {'01'} {'01'} {'10'} {'10'} {'10'} {'11'} {'11'} {'10'} {'00'} {'10'} {'00'} {'01'} {'01'} {'11'} {'10'}
>>
3 Comments
dpb
on 15 Mar 2019
Edited: dpb
on 15 Mar 2019
Yes, what you're doing wrong is using mat2str to turn the numeric values into strings first. DON'T DO THAT! :) Use the numeric values first to do the bit XOR() operation, THEN if you want to see the bit representation convert after the result has been computed. But, then you just need to apply dec2bin as I demonstrated.
Adam Danz
on 14 Mar 2019
Edited: Adam Danz
on 14 Mar 2019
Convert from char to logical matrices
jbin = (j + '0') == 97;
sbin = (sc_o + '0') == 97;
Now your data are size [80 x 2]
>> jbin(1:5,:)
ans =
5×2 logical array
0 0
0 0
1 0
0 0
1 1
If you want to perform xor element-wise,
xr = xor(jbin, sbin); %xr is a logical [80 x 2] matrix
If you want to perform xor row-wise,
xr = all((jbin + sbin) == 1,2); %xr is a logical [80 x 1] vector
Here's a look at the results of the row-wise line above. The left 2 columns are j and the right two columns are sc_o.
>> [jbin(xr,:), sbin(xr,:)]
ans = %Just the first 6 rows shown
18×4 logical array
0 0 1 1
1 0 0 1
1 1 0 0
0 1 1 0
0 0 1 1
1 1 0 0
0 Comments
See Also
Categories
Find more on Data Type Conversion 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!