| 1 |
cnh |
1.1 |
% rdslice(filename,[nx ny ...],k) returns an array of shape [nx,ny,...] |
| 2 |
|
|
% read from a direct access binary file (float or double precisision) named |
| 3 |
|
|
% by the string 'filename'. The file may contain multi-dimensional |
| 4 |
|
|
% data. Note that cumsum([nx ny ...]*k) <= length of file. |
| 5 |
|
|
% |
| 6 |
|
|
% eg. temp=rdslice('t.xyt',[160 120],4); |
| 7 |
|
|
% |
| 8 |
|
|
% rdsclice(filename,[nx ny ...],k,type) returns an array of type 'type'. |
| 9 |
|
|
% where type can be one of 'real*4' or 'real*8'. The default is 'real*8'. |
| 10 |
|
|
function [arr] = rdslice(file,N,k,varargin) |
| 11 |
|
|
|
| 12 |
|
|
% Default word-length |
| 13 |
|
|
WORDLENGTH=8; |
| 14 |
|
|
|
| 15 |
|
|
if size(varargin,2) == 1 |
| 16 |
|
|
if varargin{:} == 'real*4' |
| 17 |
|
|
WORDLENGTH=4; |
| 18 |
|
|
elseif varargin{:} == 'real*8' |
| 19 |
|
|
WORDLENGTH=8; |
| 20 |
|
|
else |
| 21 |
|
|
sprintf('Optional argument: Unknown type?') |
| 22 |
|
|
return |
| 23 |
|
|
end |
| 24 |
|
|
elseif size(varargin,2) >= 2 |
| 25 |
|
|
sprintf('Optional arguments: too many?') |
| 26 |
|
|
return |
| 27 |
|
|
end |
| 28 |
|
|
|
| 29 |
|
|
if WORDLENGTH == 4 |
| 30 |
|
|
rtype='real*4'; |
| 31 |
|
|
elseif WORDLENGTH == 8 |
| 32 |
|
|
rtype='real*8'; |
| 33 |
|
|
else |
| 34 |
|
|
sprintf('Internal error: WORDLENGTH has illegal value') |
| 35 |
|
|
return |
| 36 |
|
|
end |
| 37 |
|
|
|
| 38 |
|
|
nnn=prod(N); |
| 39 |
|
|
|
| 40 |
|
|
[fid mess]=fopen(file,'r','n'); |
| 41 |
|
|
if fid == -1 |
| 42 |
|
|
sprintf('Error while opening file:\n%s',mess) |
| 43 |
|
|
arr=0; |
| 44 |
|
|
return |
| 45 |
|
|
end |
| 46 |
|
|
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof'); |
| 47 |
|
|
if st ~= 0 |
| 48 |
|
|
mess=ferror(fid); |
| 49 |
|
|
sprintf('There was an error while positioning the file pointer:\n%s',mess) |
| 50 |
|
|
arr=0; |
| 51 |
|
|
return |
| 52 |
|
|
end |
| 53 |
|
|
[arr count]=fread(fid,nnn,rtype); |
| 54 |
|
|
if count ~= nnn |
| 55 |
|
|
sprintf('Not enough data was available to be read: off EOF?') |
| 56 |
|
|
arr=0; |
| 57 |
|
|
return |
| 58 |
|
|
end |
| 59 |
|
|
st=fclose(fid); |
| 60 |
|
|
arr=reshape(arr,N); |