Youssi
Youssi

Reputation: 63

Convert binary values to a decimal matrix

Suppose that I have a matrix a= [1 3; 4 2], I convert this matrix to binary format using this code:

a=magic(2)
y=dec2bin(a,8)
e=str2num(y(:))';

The result is :

  y =

00000001
00000100
00000011
00000010


e =

Columns 1 through 17

 0     0     0     0     0     0     0     0     0     0     0     0     0         0     0     0     0

Columns 18 through 32

 0     0     0     0     1     0     0     0     0     1     1     1     0        1     0

Now when I want to get back my original matrix I inverse the functions :

  s=num2str(e(:))';
  r=bin2dec(s)

The results I got is:

r =

    1082

What can I do to get the orignal matrix? not a number Thank you in advance

Upvotes: 2

Views: 341

Answers (2)

GameOfThrows
GameOfThrows

Reputation: 4510

You are doing extra processes which destroyed the original structure:

a=magic(2)
y=dec2bin(a,8)
r=bin2dec(y)

Here r is your answer since y has removed the matrix structure of a. To recreate your matrix, you need to:

originalmatrix = reshape(r,size(a))

originalmatrix =

 1     3
 4     2

Upvotes: 6

Youssi
Youssi

Reputation: 63

I finally got the right solution for my problem and I want to share it in case anyone need it :

a_back=reshape(bin2dec(num2str(reshape(e, 4, []))), 2, 2)

a =

 1     3
 4     2

Upvotes: 1

Related Questions