I have an array of length 256. It has either 0's and 1's of type uint8. I would like to concatenate it so that it occupies less memory and then recover the original array back. please check the eaxample

5 ビュー (過去 30 日間)
x = [1 0 1 1 1 0 0 1...........1] % uint8. length = 256. size = 256*8 = 2048 bytes
xbin = 1011100...........1 % binary form. 256 bits or 32 bytes
% from 'xbin', I need to recover 'x' and store it in variable 'y' in 'uint8' format
y = [1 0 1 1 1 0 0 1] % uint8. length = 256. size = 256*8 = 2048 bytes
  1 件のコメント
Stephen23
Stephen23 2015 年 2 月 13 日
編集済み: Stephen23 2015 年 2 月 13 日
Actually a uint8 vector with 256 elements is only 256 bytes:
>> X = round(rand(1,256)); % double
>> Y = uint8(rand(1,256)); % uint8
>> whos('X','Y')
Name Size Bytes Class Attributes
X 1x256 2048 double
Y 1x256 256 uint8
You seem to be counting bits, not bytes.

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

採用された回答

Image Analyst
Image Analyst 2015 年 2 月 13 日
You're dealing with 2048 bytes and you're worried about memory???? Oh well, anyway...
Try this:
% Generate sample 256 long array of 1's and 0's.
x = randi(2, 1, 256)-1
% Convert to a string.
charx = dec2bin(x)'
% Extract every group of 8 characters into a uint8 number.
for k = 1 : length(charx)/8
numbers(k) = uint8(bin2dec(charx(1+(k-1)*8 : k*8)));
end
% Print to command window.
numbers
  1 件のコメント
MKN
MKN 2015 年 2 月 13 日
編集済み: MKN 2015 年 2 月 13 日
Did a few lines of code to get the original array back. Worked fine. Thank You, Image Analyst

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

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 2 月 13 日
編集済み: Stephen23 2015 年 2 月 13 日
You could do this in just two lines by converting the vectors of 0 & 1 to uint32 values:
>> A = uint8(randi(2,1,256)-1);
>> B = num2cell(reshape(double(A),[],32),2);
>> C = cellfun(@(b)uint32(sum(pow2(b,31:-1:0))),B);
>> whos('A','C')
Name Size Bytes Class Attributes
A 1x256 256 uint8
C 8x1 32 uint32
The reverse conversion is even easier:
>> D = uint8(rem(floor(bsxfun(@pow2,double(C),-31:1:0)),2));
>> D = D(:).';
And we can confirm that this gives exactly the same uint8 vector:
>> find(D~=A)
ans = Empty matrix: 1-by-0
  1 件のコメント
MKN
MKN 2015 年 2 月 13 日
編集済み: MKN 2015 年 2 月 13 日
Your code too worked the way I wanted. Thank you

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

タグが未入力です。

製品

Community Treasure Hunt

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

Start Hunting!

Translated by