Home > Software engineering >  How to convert matrix with integer values to matrix binary values in MATLAB
How to convert matrix with integer values to matrix binary values in MATLAB

Time:10-24

I'm trying to create a MATLAB script that converts an 100x100 matrix of positive integers to their unsigned binary values. Example matDec=[1,2;1,2] converted to matBin=[00000001,00000010;00000001,00000010].

I tried something like:

BinI=int2bit(I,8);

where I is the initial matrix and BinI is the matrix.

But I got an 800x100 matrix as a result, meaning that the bits of each element got split into 8 elements.

CodePudding user response:

Let be

A1 =
     4    -2     4   -10
     5     3   -10    -8
     5    -7    -5     7

then

A2=dec2bin(A1)
A2 =
  12×8 char array
    '00000100'
    '00000101'
    '00000101'
    '11111110'
    '00000011'
    '11111001'
    '00000100'
    '11110110'
    '11111011'
    '11110110'
    '11111000'
    '00000111'

You are right, although in the command line the result looks as if each line is just one element, the type is char so each inidividual character is an actually a single element.

A way to obtain the sought matrix with same size as the input is using command string

sz1=size(A1);
reshape(string(dec2bin(A1)),sz1)
 = 
  3×4 string array
    "00000100"    "11111110"    "00000100"    "11110110"
    "00000101"    "00000011"    "11110110"    "11111000"
    "00000101"    "11111001"    "11111011"    "00000111"

Command string was introduced in MATLAB version 2016b.

There's no command string in previous versions.

  • Related