1 function [A,meta] = readnd(fname);
3 % READND - read a binary N-dimensional data file
5 % The function reads N-dimensional data saved by either the C or Matlab
12 % Copyright 2004-2008 W. Scott Hoge (wsh032580 at proton dot me)
14 % Licensed under the terms of the MIT License
15 % (https://opensource.org/licenses/MIT)
18 fid = fopen(fname,'rb');
19 if fid <0, error(['Couldn''t open ' fname]); end;
25 fln = fread(fid,1,'integer*4');
26 hdr = fscanf(fid,'%c',4);
27 if ~strcmp(hdr,'nddf')
28 warning(['This does not appear to be a .nd file. The file type field is ' ...
33 szln = fread(fid,1,'integer*4');
34 sz = fread(fid,szln,'integer*4');
35 hdr = fscanf(fid,'%c',4);
37 if ( strcmp(hdr(4),'c') ),
43 if strcmp( hdr(1:3), 'dbl' ),
44 data = fread(fid,cmplx*prod(sz),'double');
45 elseif strcmp( hdr(1:3), 'flt' ),
46 data = fread(fid,cmplx*prod(sz),'float');
47 elseif strcmp( hdr(1:3), 'int' ),
48 data = fread(fid,cmplx*prod(sz),'int16');
49 elseif strcmp( hdr(1:3), 'cha' ),
50 data = fread(fid,cmplx*prod(sz),'uint8');
52 fprintf('format: %s\n',hdr);
54 if ( strcmp(hdr(4),'c') ),
55 data = data(1:2:length(data)) + j * data(2:2:length(data));
57 if ( prod(size(data)) ~= prod(sz) ),
58 fprintf('declared: %10d\n',prod(sz));
59 fprintf(' read: %10d\n',length(data));
60 warning('Error: size of read data doesn''t match declared size');
62 if length(sz)==1, sz = size(data)'; end;
63 A = reshape( data, sz' );
66 if ( ftell(fid) ~= maxfln ),
68 metaln = fread(fid,1,'integer*4');
69 hdr = fscanf(fid,'%c',4);
71 if strcmp( hdr, 'meta' ),
72 meta = fread(fid,metaln,'char');
74 warning('Warning: number of bytes read from file is suspicious');
75 disp([ ftell(fid) fln ]);