diff --git a/code/tools/constructNPYheader.m b/code/tools/constructNPYheader.m new file mode 100755 index 0000000..ca2840e --- /dev/null +++ b/code/tools/constructNPYheader.m @@ -0,0 +1,88 @@ + + + +function header = constructNPYheader(dataType, shape, varargin) + + if ~isempty(varargin) + fortranOrder = varargin{1}; % must be true/false + littleEndian = varargin{2}; % must be true/false + else + fortranOrder = true; + littleEndian = true; + end + + dtypesMatlab = {'uint8','uint16','uint32','uint64','int8','int16','int32','int64','single','double', 'logical'}; + dtypesNPY = {'u1', 'u2', 'u4', 'u8', 'i1', 'i2', 'i4', 'i8', 'f4', 'f8', 'b1'}; + + magicString = uint8([147 78 85 77 80 89]); %x93NUMPY + + majorVersion = uint8(1); + minorVersion = uint8(0); + + % build the dict specifying data type, array order, endianness, and + % shape + dictString = '{''descr'': '''; + + if littleEndian + dictString = [dictString '<']; + else + dictString = [dictString '>']; + end + + dictString = [dictString dtypesNPY{strcmp(dtypesMatlab,dataType)} ''', ']; + + dictString = [dictString '''fortran_order'': ']; + + if fortranOrder + dictString = [dictString 'True, ']; + else + dictString = [dictString 'False, ']; + end + + dictString = [dictString '''shape'': (']; + +% if length(shape)==1 && shape==1 +% +% else +% for s = 1:length(shape) +% if s==length(shape) && shape(s)==1 +% +% else +% dictString = [dictString num2str(shape(s))]; +% if length(shape)>1 && s+1==length(shape) && shape(s+1)==1 +% dictString = [dictString ',']; +% elseif length(shape)>1 && s %s', tempFilename, inFilename, outFilename)); + + otherwise + fprintf(1, 'I don''t know how to concatenate files for your OS, but you can finish making the NPY youself by concatenating %s with %s.\n', tempFilename, inFilename); +end + diff --git a/code/tools/writeNPY.m b/code/tools/writeNPY.m new file mode 100755 index 0000000..844dc35 --- /dev/null +++ b/code/tools/writeNPY.m @@ -0,0 +1,25 @@ + + +function writeNPY(var, filename) +% function writeNPY(var, filename) +% +% Only writes little endian, fortran (column-major) ordering; only writes +% with NPY version number 1.0. +% +% Always outputs a shape according to matlab's convention, e.g. (10, 1) +% rather than (10,). + + +shape = size(var); +dataType = class(var); + +header = constructNPYheader(dataType, shape); + +fid = fopen(filename, 'w'); +fwrite(fid, header, 'uint8'); +fwrite(fid, var, dataType); +fclose(fid); + + +end +