function [Ary,Hdr] = readZMX(F,SkipLines) %USAGE: [Ary,Hdr] = readZMX( Zemax_File,SkipLines ) %Reads data from Zemax text-output files % such as are written by the 'text' % option on most Zemax windows. %The function works by ignoring the text % headers of the file, and scanning down % to the data. %MODIFICATION: 13 May, 2008: % Code changed so that it can also read ZMX files with % only a single number per line. The function now % assumes the data start is at the first line that % contains only numbers. %MODIFIATION: 31 May, 2008: % Optional input argument "SkipLines" added. If this argument % is entered, the function skips the requested number of lines, % then reads as numerical with testing. % %INPUTS: % F: The Zemax-generated text file % SkipLine: If entered, the function skips this many lines, % and reads the rest without error checking. %OUTPUTS: % Ary: The 2-D data in the Zemax file % Hdr: If requested, this is a character matrix where each % row is a header line. % %Test for file: fid = -1; Fa = exist(F); if Fa == 2 %Open file: fid = fopen(F,'r'); end if fid == -1 disp(['File: ' F ' Not Found!']) return end %Test for requested "Fast Mode" read: if nargin == 1 %Not asked to skip lines SkipLines = -1; end % if SkipLines == -1 %Evaluate all lines %-- proceed with 'safe' read %Make array of valid ASCII codes for numbers only: Ncodes = '+-.0123456789Ee'; %Add space and tab to Ncodes (ASCII 32 and 9): Ncodes = [char(9) char(32) Ncodes]; %ASCII code for space: spc = double(' '); % Ary = []; Hdr = []; %Scan File: I = 1; while 1 %Read next line in file: line = fgetl(fid); %Test for End of Data: if ~isstr(line) %End of Data: quit function and return break %(jump out of while loop) end %Check for Headder Lines: if isempty(line) %Line is blank -- add to header array: Hdr = char(Hdr,line); elseif all(double(line)==spc) %Line is all spaces: add to header array: Hdr = char(Hdr,line); elseif isempty(setdiff(line,Ncodes)) %Line is all numbers: add to data array: Tmp = sscanf(line,'%f')'; Ary(I,:) = Tmp; I = I+1; else %Must be text header line: %Add to header array: Hdr = char(Hdr,line); end %(check line) end %(while: safe read) else %Fast Read: if SkipLines >=1 %Skip the header lines: for ii = 1:SkipLines line = fgetl(fid); end end %Read Data: Ary = []; Hdr = []; I = 1; %Scan File: while 1 %Read next line in file: line = fgetl(fid); %Test for End of Data: if ~isstr(line) %End of Data: quit function and return break %(jump out of while loop) end Tmp = sscanf(line,'%f')'; Ary(I,:) = Tmp; I = I+1; end %(while: fast read) end %Fast Read % %Close file and exit: fclose(fid);