


PURPOSE: read the size of an (ESRI) ASCII grid from the header information
without loading the data, eg. for preallocating memory.
-------------------------------------------------------------------
USAGE: [rows, cols] = get_gridsize(file)
where:
[file] filename (incl path) of the ASCII grid.
-------------------------------------------------------------------------
OUTPUTS:
[rows, cols] are the rows and columns as given in the header file
-------------------------------------------------------------------
NOTES: Currently only supports ESRIs ASCII grid format header.
Designed to read import grid size for preallocating memory.
SEE ALSO: asciigrid2mat, hdrload

0001 function [rows, cols] = get_gridsize(file) 0002 % PURPOSE: read the size of an (ESRI) ASCII grid from the header information 0003 % without loading the data, eg. for preallocating memory. 0004 % ------------------------------------------------------------------- 0005 % USAGE: [rows, cols] = get_gridsize(file) 0006 % where: 0007 % [file] filename (incl path) of the ASCII grid. 0008 % ------------------------------------------------------------------------- 0009 % OUTPUTS: 0010 % [rows, cols] are the rows and columns as given in the header file 0011 % 0012 % ------------------------------------------------------------------- 0013 % NOTES: Currently only supports ESRIs ASCII grid format header. 0014 % Designed to read import grid size for preallocating memory. 0015 % 0016 % SEE ALSO: asciigrid2mat, hdrload 0017 0018 % Felix Hebeler, Geography Dept., University Zurich, March 2006. 0019 0020 %% parameter 0021 hdrlines=2; %ascii grid has 6 header lines, but we only need the first 2 0022 0023 %% check number and type of arguments 0024 if nargin < 1 0025 error('Function requires one input argument'); 0026 elseif ~ischar(file) 0027 error('Input argument must be a string representing a filename'); 0028 end 0029 0030 %% Open the file 0031 fid = fopen(file); 0032 if fid==-1 0033 error('File not found or permission denied'); 0034 end 0035 0036 max_line = 0; 0037 0038 %% Start processing. 0039 line = fgetl(fid); 0040 if ~ischar(line) 0041 disp('Warning: file contains no header and no data') 0042 end; 0043 0044 0045 %% We loop through the file for the first [hdrlines] lines 0046 for no_lines=1:hdrlines 0047 max_line = max([max_line, length(line)]); 0048 eval(['line', num2str(no_lines), '=line;']); 0049 line = fgetl(fid); 0050 end 0051 % and close it again 0052 fclose(fid); 0053 0054 %% parse the info from the first two lines 0055 % only works for ESRI ascii headers 0056 cols=str2num(line1(strfind(line1,' ')+1:end)); 0057 rows=str2num(line2(strfind(line1,' ')+1:end));