How to represent Bitxor to mod in matlab - matlab

I want to implement xor bitwise together. For example, I have two bits pair that are 6 (110) and 3 (011). Now I want to implement bitwise xor of two inputs. It can do by bitxor function in matlab.
out=bitxor(6,3);%output is 5
But I want to implement the scheme by mod function instead of bitxor. How to do it by matlab?Thank you so much. it is my code
out=mod(6+3,2^3) %2^3 because Galois field is 8 (3 bits)

Code
function out = bitxor_alt(n1,n2)
max_digits = ceil(log(max(n1,n2)+1)/log(2));%// max digits binary representation
n1c = dec2bin(n1,max_digits); %// first number as binary in char type
n2c = dec2bin(n2,max_digits); %// second number as binary in char type
n1d = n1c-'0'; %// first number as binary in double type
n2d = n2c-'0'; %// second number as binary in double type
out = bin2dec(num2str(mod(n1d+n2d,2),'%1d')); %// mod used here
return;

Related

Convert a decimal number that is not integer to base 4 in Matlab?

Is there a way to convert a decimal number between $0$ and $1$ that is not integer to base 4 in Matlab? E.g. if I put 2/5 I want to get 0.12121212... (with some approximation I guess)
The function dec2base only works for integers.
Listed in this post is a vectorized approach that works through all possible combinations of digits to select the best one for the final output as a string. Please note that because of its very nature of creating all possible combinations, it would be memory intensive and slower than a recursive approach, but I guess it could be used just for fun or educational purposes!
Here's the function implementation -
function s = dec2base_float(d,b,nde)
%DEC2BASE_FLOAT Convert floating point numbers to base B string.
% DEC2BASE_FLOAT(D,B) returns the representation of D as a string in
% base B. D must be a floating point array between 0 and 1.
%
% DEC2BASE_FLOAT(D,B,N) produces a representation with at least N decimal digits.
%
% Examples
% dec2base_float(2/5,4,4) returns '0.1212'
% dec2base_float(2/5,3,6) returns '0.101211'
%// Get "base power-ed scaled" digits
scale = b.^(-1:-1:-nde);
%// Calculate all possible combinations
P = dec2base(0:b^nde-1,b,nde)-'0';
%// Get the best possible combination ID. Index into P with it and thus get
%// based converted number with it
[~,idx] = min(abs(P*scale(:) - d));
s = ['0.',num2str(P(idx,:),'%0.f')];
return;
Sample runs -
>> dec2base_float(2/5,4,4)
ans =
0.1212
>> dec2base_float(2/5,4,6)
ans =
0.121212
>> dec2base_float(2/5,3,6)
ans =
0.101211

MATLAB: How to discard overflow digits binary addition?

I want to know if it's possible in MATLAB to discard overflow digits in MATLAB when I add two binary numbers.
I've only been able to find how to have a least number of binary digits, but how to I set a maximum number of digits?
For example:
e = dec2bin(bin2dec('1001') + bin2dec('1000'))
That gave me:
e =
10001
How do I get only '0001'?
dec2bin will always give you the minimum amount of bits to represent a number. If you would like to retain the n least significant digits, you have to index into the string and grab those yourself.
Specifically, if you want to retain only the n least significant digits, given that you have a base-10 number stored in num, you would do this:
out = dec2bin(num);
out = out(end-n+1:end);
Bear in mind that this performs no error checking. Should n be larger than the total number of bits in the string, you will get an out of bounds error. I'm assuming you're smart enough to use this and know what you're doing.
So for your example:
e = dec2bin(bin2dec('1001') + bin2dec('1000'));
n = 4, and so:
>> n = 4;
>> e = e(end-n+1:end)
e =
0001
Here is a more robust (but less efficient, I fear) way: What you describe is exactly the modulo operation. A 4-bit binary number is the remainder after a division by 0b10000 = 16. This can be done using the mod function in MATLAB.
>> e = dec2bin(mod(bin2dec('1001') + bin2dec('1000'),16),4)
e =
0001
Note: I added 4 as additional argument to the dec2bin function, so the output will always be 4-bit wide.
This can of course be generalized to any bit width: If you want to add 8-bit numbers, you will need the remainder of the division by 0b1'0000'0000 = 256, for example
>> e = dec2bin(mod(bin2dec('10011001') + bin2dec('10001000'),256),8)
e =
00100001
Or for shorter numbers, e.g. 2-bit wide, it is 0b100 = 4:
>> e = dec2bin(mod(bin2dec('10') + bin2dec('11'),4),2)
e =
01

how to sum digits in a multi-digit number Matlab

I wonder how to sum digits for a multi-digit number in Matlab.
For example 1241= 1+2+4+1 = 8
String-based answer:
>> n = 1241;
>> sum(int2str(n)-48)
ans =
8
The number is first converted to a string representation using int2str, then the ASCII code for '0' (i.e. 48) is subtracted from the ASCII code for each element of the string, producing a numeric vector. This is then summed to get the result.
A = 35356536576821;
A = abs(A);
xp = ceil(log10(A)):-1:1;
while ~isscalar(xp)
A = sum(fix(mod(A,10.^xp)./10.^[xp(2:end) 0]));
xp = ceil(log10(A)):-1:1;
end
this is the numeric approach
This one is the solution is character approach:
A = '35356536576821';
A = char(regexp(A,'\d+','match'));
while ~isscalar(A)
A = num2str(sum(A - '0'));
end
Both, first take the absolute number (strip the minus) then: the numeric one counts with log10() how many digits a number has and through modulus and divisions extracts the digits which are summed, while the char approach convert to numeric digits with implicit conversion of - '0', sums and converts back to string again.
Another all-arithmetic approach:
n = 1241; %// input
s = 0; %// initiallize output
while n>0 %// while there is some digit left
s = s + mod(n-1,10)+1; %// sum rightmost digit
n = floor(n/10); %// remove that digit
end
Youcan use this code
sum(int2str(n)-48)
where n, is your input number.

Bitwise XOR operation to scramble two character matrices by generating a truth table

I need to perform the XOR operation for four characters where each of them have a bit representation as follows:
A = 00
G = 01
C = 10
T = 11
I need to create a table that XORs two characters together which gives the values for all combinations of XORing pairs of characters in the following way.
XOR A G C T
A A G C T
G G A T C
C C T A G
T T C G A
To obtain the output, you need to convert each character into its bit representation, XOR the bits, then use the result and convert it back into the right character. For example, consulting the third row and second column of the table, by XORing C and G:
C = 10
G = 01
C XOR G = 10 XOR 01 = 11 --> T
I would ultimately like to apply this rule to scrambling characters in a 5 x 5 matrix.
As an example:
A = 'GATT' 'AACT' 'ACAC' 'TTGA' 'GGCT'
'GCAC' 'TCAT' 'GTTC' 'GCCT' 'TTTA'
'AACG' 'GTTA' 'ACGT' 'CGTC' 'TGGA'
'CTAC' 'AAAA' 'GGGC' 'CCCT' 'TCGT'
'GTGT' 'GCGG' 'GTTT' 'TTGC' 'ATTA'
B = 'ATAC' 'AAAT' 'AGCT' 'AAGC' 'AAGT'
'TAGG' 'AAGT' 'ATGA' 'AAAG' 'AAGA'
'TAGC' 'CAGT' 'AGAT' 'GAAG' 'TCGA'
'GCTA' 'TTAC' 'GCCA' 'CCCC' 'TTTC'
'CCAA' 'AGGA' 'GCAG' 'CAGC' 'TAAA'
I would like to generate a matrix C such that each element of A gets XORed with its corresponding element in B.
For example, considering the first row and first column:
A{1,1} XOR B{1,1} = GATT XOR ATAC = GTTG
How can I do this for the entire matrix?
Looks like you're back for some more!
First, let's define the function letterXOR that takes two 4-character strings and XORs both strings corresponding to that table that you have. Recalling from our previous post, let's set up a lookup table where a unique two-bit string corresponds to a letter. We can use the collections.Map class to help us do this. We will also need the inverse lookup table using a collections.Map class where given a letter, we produce a two-bit string. We need to do this as you want to convert each letter into its two bit representation, and we need the inverse lookup to do this. After, we XOR the bits individually, then use the forward lookup table to get back to where we started. As such:
function [out] = letterXOR(A,B)
codebook = containers.Map({'00','11','10','01'},{'A','T','G','C'}); %// Lookup
invCodebook = containers.Map({'A','T','G','C'},{'00','11','10','01'}); %// Inv-lookup
lettersA = arrayfun(#(x) x, A, 'uni', 0); %// Split up each letter into a cell
lettersB = arrayfun(#(x) x, B, 'uni', 0);
valuesA = values(invCodebook, lettersA); %// Obtain the binary bit strings
valuesB = values(invCodebook, lettersB);
%// Convert each into a matrix
valuesAMatrix = cellfun(#(x) double(x) - 48, valuesA, 'uni', 0);
valuesBMatrix = cellfun(#(x) double(x) - 48, valuesB, 'uni', 0);
% XOR the bits now
XORedBits = arrayfun(#(x) bitxor(valuesAMatrix{x}, valuesBMatrix{x}), 1:numel(A), 'uni', 0);
%// Convert each bit pair into a string
XORedString = cellfun(#(x) char(x + 48), XORedBits, 'uni', 0);
%// Access lookup, then concatenate as a string
out = cellfun(#(x) codebook(x), XORedString);
Let's go through the above code slowly. The inputs into letterXOR are expected to be a character array of letters that are composed of A, T, G and C. We first define the forward and reverse lookups. We then split up each character of the input strings A and B into a cell array of individual characters, as looking up multiple keys in your codebook requires it to be this way. We then figure out what the bits are for each character in each string. These bits are actually strings, and so what we need to do is convert each string of bits into an array of numbers. We simply cast the string to double and subtract by 48, which is the ASCII code for 0. By converting to double, you'll either get 48 or 49, which is why we need to subtract with 48.
As such, each pair of bits is converted into a 1 x 2 array of bits. We then take each 1 x 2 array of bits between A and B, use bitxor to XOR the bits. The outputs at this point are still 1 x 2 arrays. As such, we need to convert each array into a string of bits, then use our forward lookup table to look up the character equivalent of these bits. After this, we concatenate all of the characters together to make the final string for the output.
Make sure you save the above in a function called letterXOR.m. Once we have this, we now simply have to use one cellfun call that will XOR each four-element string in your cell array and we then output our final matrix. We will use arrayfun to do that, and the input into arrayfun will be a 5 x 5 matrix that is column major defined. We do this as MATLAB can access elements in a 2D array using a single value. This value is the column major index of the element in the matrix. We define a vector that goes from 1 to 25, then use reshape to get this into the right 2D form. The reason why we need to do this is because we want to make sure that the output matrix (which is C in your example) is structured in the same way. As such:
ind = reshape(1:25, 5, 5); %// Define column major indices
C = arrayfun(#(x) letterXOR(A{x},B{x}), ind, 'uni', 0); % // Get our output matrix
Our final output C is:
C =
'GTTG' 'AACA' 'ATCG' 'TTAC' 'GGTA'
'CCGT' 'TCGA' 'GACC' 'GCCC' 'TTCA'
'TATT' 'TTCT' 'ATGA' 'TGTT' 'ATAA'
'TGTC' 'TTAC' 'ATTC' 'AAAG' 'AGCG'
'TGGT' 'GTAG' 'AGTC' 'GTAA' 'TTTA'
Good luck!

Matlab binary encoding

I have a vector containing a series of integers, and what I want to do is take all numbers, convert them into their corresponding binary forms, and concatenate all of the resulting binary values together. Is there any easy way to do this?
e.g. a=[1 2 3 4] --> b=[00000001 00000010 00000011 00000100] --> c=00000001000000100000001100000100
Try:
b = dec2bin(a)
As pointed out by the other answers, the function DEC2BIN is one option that you have to solve this problem. However, as pointed out by this other SO question, it can be a very slow option when converting a large number of values.
For a faster solution, you can instead use the function BITGET as follows:
a = [1 2 3 4]; %# Your array of values
nBits = 8; %# The number of bits to get for each value
nValues = numel(a); %# The number of values in a
c = zeros(1,nValues*nBits); %# Initialize c to an array of zeroes
for iBit = 1:nBits %# Loop over the bits
c(iBit:nBits:end) = bitget(a,nBits-iBit+1); %# Get the bit values
end
The result c will be an array of zeroes and ones. If you want to turn this into a character string, you can use the function CHAR as follows:
c = char(c+48);
Yes, use dec2bin, followed by string concatenation.