Convert matrix elements from decimal to binary - matlab

I have a matrix with decimal elements. I want to convert every element in this matrix to binary with a resolution of 8. What function should I use?

Use dec2bin:
>> dec2bin([10; 100; 255], 8)
ans =
00001010
01100100
11111111
The second parameter tells it to use at least N bits (where N==8 here).

Related

How to find the nearest match for an integer in a given matrix?

I have two matrices. Matrix A(2048,64) and matrix B(10000,64). Values in each element of these matrices is a binary bit, so each row is a representation of a 64-bit binary value, so each row of the matrix has a magnitude between 2^63 and 2^0; Most Significant Bit to Least Significant Bit, respectively.
Problem:
For each row of A I want to find the value in B which is the closest to it in an absolute, numeric sense.
Consider A(i,1:64) being a binary representation of decimal value Xi, and B(j,1:64) a binary representation of decimal value Yj. So at the first step I want to find the best j such that X1 or A(1,1:64) has the closest numeric value to the element at Yj, i.e. abs(X1-Yj) is minimized among all possible values for j.
The below image, brought from here, describes my problem rather well, but the difference is that each of my values are contained in a row of a matrix containing 64 elements.
I tried to convert the 64-bit values to decimal, however dec2bin supports values up to 56-bit only.
You can divide your 64-bit number into two 32-bit pieces, b1 and b2, convert them to decimal values d1 and d2, then combine them into a uint64 value that has enough precision to hold the result.
bin2uint64 = #(b) uint64(bin2dec(b(:,1:32)))*(2^32) + uint64(bin2dec(b(:,33:64)));
(This assumes that you have your data in the same format required by bin2dec, i.e. a vector of char. If you have a vector of numeric values, just add in a b = char(b+'0');)
Given an initial value
>> b = 1100110010111100101101111010100010101010010011010010000110011010
>> d = bin2uint64(b)
d = 14752868414398472602
>> r = dec2bin(d, 64)
r = 1100110010111100101101111010100010101010010011010010000110011010
>> any(b-r)
ans = 0
Since b-r gives all zeros, the values are identical. You can pass the entire nx64 matrix as b and it will convert all of the values at once.
>> bin2uint64(char(randi([0 1], 20, 64) + '0'))
ans =
4169100589409210726
8883634060077187622
15399652840620725530
12845470998093501747
14561257795005665153
1133198980289431407
13360302497937328511
563773644115232568
8825360015701340662
2543400693478304607
11786523850513558107
8569436845019332309
2720129551425231323
5937260866696745014
4974981393428261150
16646060326132661642
5943867124784820058
2385960312431811974
13146819635569970159
6273342847731389380
You'll notice that I manually converted my random array to char. Assuming your input is numeric, you'll have to convert it first:
Achar = char(A + '0');
Yes, this is a pain, MATLAB should have included a destination type parameter in bin2dec, but they didn't. Now you can use your linked solution to find the matchings.
Converting your values:
Assuming your matrices A and B contain the numeric values 0 and 1, you can easily convert the rows to uint64 data types without precision loss using the bitset and sum functions (and bsxfun for a small efficiency boost):
result = sum(bsxfun(#(bit, V) bitset(uint64(0), bit, V), 64:-1:1, A), 2, 'native');
Compared to the solution from beaker, this one is over 4 times faster for a 10,000 row matrix:
% Sample data:
A = randi([0 1], 10000, 64);
% Test functions:
bin2uint64 = #(b) uint64(bin2dec(b(:,1:32)))*(2^32) + uint64(bin2dec(b(:,33:64)));
beaker_fcn = #(A) bin2uint64(char(A+'0'));
gnovice_fcn = #(A) sum(bsxfun(#(b, V) bitset(uint64(0), b, V), 64:-1:1, A), 2, 'native');
% Accuracy test:
isMatch = isequal(beaker_fcn(A), gnovice_fcn(A)); % Return "true"
% Timing:
timeit(#() beaker_fcn(A))
ans =
0.022865378234183
timeit(#() gnovice_fcn(A))
ans =
0.005434031911843
Computing nearest matches:
You provide a link to some solutions for finding the nearest matches for A in B. However, the fact that you are using unsigned integer types requires some modification. Specifically, order matters when subtracting values due to integer overflow. For example uint64(8) - uint64(1) gives you 7, but uint64(1) - uint64(8) gives you 0.
Here's the modified solution for unsigned integers, applied to the sample data you provide:
A = uint64([1 5 7 3 2 8]);
B = uint64([4 12 11 10 9 23 1 15]);
delta = bsxfun(#(a, b) max(a-b, b-a), A(:), reshape(B, 1, []));
[~, index] = min(delta, [], 2);
result = B(index)
result =
1×6 uint64 row vector
1 4 9 4 1 9 % As expected!

uencode -signal processing matlab

i need to quantize and encode an input signal using matlab so i will use uencode function . The problem is that i am confused about its process , the description says that it quantize and encode the input as integer and then he has displayed an example :
u = -1:0.01:1;
y = uencode(u,3);
plot(u,y,'.')
The output is just integers , can somebody just explain what this integers exactly are ?? and if i need the binary codes of the input u what i must do to get them ?
uencode takes the range of floating point numbers between -1.0 and 1.0, and maps it to the integers from 0 to (2^n)-1.
For example, with n=8, the possible integers are 0 to 255. -1.0 gets mapped to 0, +1.0 gets mapped to 255, and all decimal values in between get mapped to the closest integer.
In the code example you gave, n=3, so it is mapping to the integers 0 to 7. The plot shows horizontal lines because with so few integers available to map to, many floating point values map to the same integer.
To convert a base 10 integer to a base 2 binary string, use the function dec2bin.
>> dec2bin(5)
ans =
101
>> dec2bin(17)
ans =
10001
If you wanting leading zeros, say so that they are always 8 bits long, use the minimum length as a second argument:
>> dec2bin(5, 8)
ans =
00000101

Octave nan function with argument "single"

The code I'm reading has a line:
someData = nan(3, 4, 5, "single")
I can't find the documentation for the "nan" function, but this code appears to generate a 3x4x5 matrix of NaN. However, I don't know what "single" does. Replacing it with a random other string gets "error: NaN: invalid data type specified", and replacing it with "double" appears to give the same result. What is the function of the "single"?
It makes the resulting matrix of nan a matrix that is of the single-precision data type which contains single-precision floating-point numbers. If you want single precision, you need to specify this explicitly, otherwise Octave and MATLAB will use double-precision by default.
You can check the class of the output using class.
class(nan(3, 4, 5, 'single'))
% 'single'
class(nan(3, 4, 5))
% 'double'
As far as looking the same, they will look the same until you start trying to store numbers that exceed the range of numbers that can be represented with single-precision floating point representation. This is because single precision numbers use half the amount of memory that double precision numbers do.
a = nan(1, 1, 'single');
a(1) = 1e-64
% 0
b = nan(1, 1);
b(1) = 1e-64
% 1.000e-64
Also if we inspect the variables with whos we can confirm the size difference.
a = nan(1,1,'single');
b = nan(1,1)
whos('a', 'b')
% Variables in the current scope:
%
% Attr Name Size Bytes Class
% ==== ==== ==== ===== =====
% a 1x1 4 single
% b 1x1 8 double

How to represent Bitxor to mod in 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;

Performing Bit modification on Floating point numbers in Matlab

I'm working in Matlab using Non-negative Matrix factorization to decompose a matrix into two factors. Using this I get from A two double precision floating point matrices, B and C.
sample results are
B(1,1) = 0.118
C(1,1) = 112.035
I am now trying to modify specific bits within these values but using the bitset function on either values I get an error because bitset requires unsigned integers.
I have also tried using dec2bin function, which I assumed would convert decimals to binary but it returns '0' for B(1,1).
Does anyone know of any way to deal with floats at bit level without losing precision?
You should look into the typecast and bitset functions. (Doc here and here respectively). That lets you do stuff like
xb = typecast( 1.0, 'uint64' );
xb = bitset( xb, 10, 1 );
typecast( xb, 'double' );
The num2hex and hex2num functions are your friends. (Though not necessarily very good friends; hexadecimal strings aren't the best imaginable form for working on binary floating-point numbers. You could split them into, say, 8-nybble chunks and convert each to an integer.)
From the MATLAB docs:
num2hex([1 0 0.1 -pi Inf NaN])
returns
ans =
3ff0000000000000
0000000000000000
3fb999999999999a
c00921fb54442d18
7ff0000000000000
fff8000000000000
and
num2hex(single([1 0 0.1 -pi Inf NaN]))
returns
ans =
3f800000
00000000
3dcccccd
c0490fdb
7f800000
ffc00000