How can i replace 0 by -1 in all binary number till 256 as 00000000, 00000001, 00000010, 00000011, 00000100, ..........​​.........​.​........​..​...., 11111111 ?

2 ビュー (過去 30 日間)
Without using loops
  1 件のコメント
Guillaume
Guillaume 2015 年 7 月 17 日
If you replace the 0s by 1 in all the binary numbers, then the result is 255 for all of them.

サインインしてコメントする。

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 17 日
編集済み: Azzi Abdelmalek 2015 年 7 月 17 日
a=dec2bin(0:255)
out=strrep(cellstr(a),'0','1')
  4 件のコメント
kailash kumar
kailash kumar 2015 年 7 月 17 日
Sir it turnout to a 256X8 matrix , but all elements are 1. but it should be 0 to 255 binary numbers, in which all 0 should be replaced by '-1'.
Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 17 日
a=dec2bin(0:255)
out=strrep(cellstr(a),'0','-1')

サインインしてコメントする。


arich82
arich82 2015 年 7 月 17 日
編集済み: arich82 2015 年 7 月 17 日
[Edited to use 0:255 instead of 1:256]
n = 8;
a = dec2bin(0:n-1) - '0'
returns a as a matrix of doubles:
a =
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Now just use a logical mask to change 0 --> -1:
a(a == 0) = -1
which returns
a =
-1 -1 -1
-1 -1 1
-1 1 -1
-1 1 1
1 -1 -1
1 -1 1
1 1 -1
1 1 1
For your case, use n = 256. The complete solution (I think) is:
n = 256;
a = dec2bin(0:n-1) - '0';
a(a==0) = -1;
disp(a);
Please accept this answer if it helps, or let me know in the comments if it's not what you're looking for.
  1 件のコメント
arich82
arich82 2015 年 7 月 17 日
Alternative to dec2bin: bitget.
Unfortunately, it seems bitget can only get either several bits from a scalar, or a single bit from each element of an array. Wrapping it in bsxfun gets around this apparent limitation:
a = bsxfun(@bitget, [0:255].', 8:-1:1);
a(a == 0) = -1;
Not an issue for your use case, but for much larger arrays, I'd expect bitget to be much quicker than all of the character conversions going on in the dec2bin version, though I could be wrong. (You'd also want to use nextpow2 to get all digits for the more general case).
n = 256;
a = bsxfun(@bitget, (0:n - 1).', nextpow2(n - 1):-1:1);
a(a == 0) = -1;
There's also de2bi if you have the appropriate toolbox (Communications System Toolbox?):

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by