0

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.

11
  • "string of bits" you say, which should have length 8 right? So it is the right size? Commented Oct 23, 2022 at 12:50
  • @AnderBiguri Yes , each values varies from 0-255 , so 8 bits is the right size.The problem is that each string is divided into 8 different elements Commented Oct 23, 2022 at 12:53
  • No, a string is a "char array", an array of individual characters. Commented Oct 23, 2022 at 13:13
  • Perhaps you can use convertCharsToStrings Commented Oct 23, 2022 at 13:14
  • @AnderBiguri I tried to , but all i got was a single string.I also tried this command inside a for loop , for each individual element. Commented Oct 23, 2022 at 13:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use cellstr here instead of string in any version of MATLAB, you'll end up with a cell array of chars instead of a string array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.