how to perform xor of two bits in matab

2 次查看(过去 30 天)
  • 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??

回答(2 个)

dpb
dpb 2019-3-14
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 个评论
Ayesha Punjabi
Ayesha Punjabi 2019-3-15
i think i might be doing something wrong pleae help
dpb
dpb 2019-3-15
编辑:dpb 2019-3-15
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
Adam Danz 2019-3-14
编辑:Adam Danz 2019-3-14
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by