How to convert decimal matrix matrix into binary matrix?

조회 수: 20 (최근 30일)
Mudasir Ahmed
Mudasir Ahmed 2016년 10월 23일
댓글: Mudasir Ahmed 2016년 10월 25일
hi
I want to convert 3 by 4 decimal matrix into equivalent 3 by 4 binary matrix
e.g
a=[10 9 8 7
9 7 9 6
1 2 3 8]
b=[1010 1001 1000 0111
1001 0111 1001 0110
0001 0010 0011 1000]
kindly help me I will be highly thankful to you
regards, mudasir

채택된 답변

Guillaume
Guillaume 2016년 10월 23일
Note there's not such thing as
b=[1010 1001 1000 0111
1001 0111 1001 0110
0001 0010 0011 1000]
in matlab. Binary matrices don't exist in matlab.
The closest you can get is a cell array of string, which you'll obtain with:
a = [10 9 8 7
9 7 9 6
1 2 3 8]
b = reshape(cellstr(dec2bin(a)), size(a))
which produces:
b =
3×4 cell array
'1010' '1001' '1000' '0111'
'1001' '0111' '1001' '0110'
'0001' '0010' '0011' '1000'
  댓글 수: 2
Mudasir Ahmed
Mudasir Ahmed 2016년 10월 23일
Dear sir,
Thank you so much, it's now working.
sir whats the procedure of returning it back to the original form like
a = [10 9 8 7
9 7 9 6
1 2 3 8]
and my second question is if I want to send bit from one set to another set like
'1010' and '1001'
if I cut after 3rd digit in 1010 and replace 4th digit "0" with the 4th digit of 1001 like : ans: (1011)
how i do the above operation.
kindly sir guide me. thanks
Guillaume
Guillaume 2016년 10월 23일
a = reshape(bin2dec(b), size(b))
to get the original a back.
As far as matlab is concerned, there's nothing binary about b, they're just strings (that happen to contain 0 and 1). You can of course manipulate strings and replace characters:
c = cellfun(@(s) [s(1:3), '1'], b, 'UniformOutput', false);
But if all you want to do is change a bit, then you're better off staying with the original decimal array and use bitset:
bitset(a, 1, 1) %set bit 1 to 1

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andriy Kavetsky
Andriy Kavetsky 2016년 10월 23일
Use dec2base(a,2) command to get string array of binary numbers and str2num(dec2base(a,2)) to convert string into numbers
  댓글 수: 3
Walter Roberson
Walter Roberson 2016년 10월 23일
a=[10 9 8 7
9 7 9 6
1 2 3 8];
dec2base(a)
gives a char array as output.
To convert back you need to use base2dec()
Mudasir Ahmed
Mudasir Ahmed 2016년 10월 25일
Dear sir,
I have number a=50 I want to convert it to binary, then I randomly choose the position in a binary string and compliment it Like
a=50
b=dec2bin(a)
b=110010
position=4
b becomes
b=110110
how i do this sir.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by