Conversion of a binary matrix to decimal matrix

5 ビュー (過去 30 日間)
Mehmet
Mehmet 2022 年 3 月 14 日
コメント済み: Mehmet 2022 年 3 月 14 日
Hello everyone,
I wonder if there is an easier way to convert a binary matrix to a decimal matrix?
For example: A = [1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0; 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0] (2x16 matrix) will be converted into B = [255 0; 15 240] (2x2 matrix). So, 8 bit binary numbers in the original matrix will be converted into decimal numbers. Or, in general, an Mx8N binary matrice will be converted into an MxN decimal matrice.
I know i can do it by using for loops and binaryVectorToDecimal or bi2de functions.
However, there might be a more easier way to do it by utilizing another built-in functions.
Thanks in advance,

採用された回答

Stephen23
Stephen23 2022 年 3 月 14 日
編集済み: Stephen23 2022 年 3 月 14 日
The most efficient approach would probably be to avoid type conversion (e.g. to character) and to avoid BIN2DEC.
It is just as easy to do the whole thing with basic numeric operations:
A = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0;0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0]
A = 2×16
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0
M = reshape(pow2(7:-1:0)*reshape(A.',8,[]),[],size(A,1)).'
M = 2×2
255 0 15 240
  2 件のコメント
Jan
Jan 2022 年 3 月 14 日
編集済み: Jan 2022 年 3 月 14 日
This is 5 times faster than the bin2dec approach.
To my surprise 2.^(7:-1:0) is faster than pow2(7:-1:0).
Mehmet
Mehmet 2022 年 3 月 14 日
Thanks. This is so cool!

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

その他の回答 (1 件)

Matt J
Matt J 2022 年 3 月 14 日
編集済み: Matt J 2022 年 3 月 14 日
A = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0;0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0];
e=kron(speye(2),2.^(7:-1:0)');
B = A*e
B = 2×2
255 0 15 240

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by