comparison m-toolbox/classes/+utils/@helper/dzip.m @ 0:f0afece42f48

Import.
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Wed, 23 Nov 2011 19:22:13 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f0afece42f48
1 function Z = dzip(M)
2 % DZIP - losslessly compress data into smaller memory space
3 %
4 % USAGE:
5 % Z = dzip(M)
6 %
7 % VARIABLES:
8 % M = variable to compress
9 % Z = compressed output
10 %
11 % NOTES: (1) The input variable M can be a scalar, vector, matrix, or
12 % n-dimensional matrix
13 % (2) The input variable must be a non-complex and full (meaning
14 % matrices declared as type "sparse" are not allowed)
15 % (3) Permitted input types include: double, single, logical,
16 % char, int8, uint8, int16, uint16, int32, uint32, int64,
17 % and uint64.
18 % (4) In testing, DZIP compresses several megabytes of data per
19 % second.
20 % (5) In testing, random matrices of type double compress to about
21 % 75% of their original size. Sparsely populated matrices or
22 % matrices with regular structure can compress to less than
23 % 1% of their original size. The realized compression ratio
24 % is heavily dependent on the data.
25 % (6) Variables originally occupying very little memory (less than
26 % about half of one kilobyte) are handled correctly, but
27 % the compression requires some overhead and may actually
28 % increase the storage size of such small data sets.
29 % One exception to this rule is noted below.
30 % (7) LOGICAL variables are compressed to a small fraction of
31 % their original sizes.
32 % (8) The DUNZIP function decompresses the output of this function
33 % and restores the original data, including size and class type.
34 % (9) This function uses the public domain ZLIB Deflater algorithm.
35 % (10) Carefully tested, but no warranty; use at your own risk.
36 % (11) Michael Kleder, Nov 2005
37
38 s = size(M);
39 c = class(M);
40 cn = strmatch(c,{'double','single','logical','char','int8','uint8',...
41 'int16','uint16','int32','uint32','int64','uint64'});
42 if cn == 3 | cn == 4
43 M=uint8(M);
44 end
45 M=typecast(M(:),'uint8');
46 M=[uint8(cn);uint8(length(s));typecast(s(:),'uint8');M(:)];
47 f=java.io.ByteArrayOutputStream();
48 g=java.util.zip.DeflaterOutputStream(f);
49 g.write(M);
50 g.close;
51 Z=typecast(f.toByteArray,'uint8');
52 f.close;
53 return