MATLAB: Reading a text file

fileif statementtext file

Hello I have this piece of code for opening a text file, but I cannot interpret some part of the code.
fid = fopen(NBIFileName);
%loops through the file and read each record in sequence
while ~feof(fid)
NBIRecord = fgetl(fid);
if feof(fid), break, end
% selects only valid highway bridges
if( NBIRecord( 19)=='1')&(NBIRecord(374) == 'Y') & ...
((NBIRecord(200)=='1')| ...
(NBIRecord(200)=='5')|(NBIRecord(200) == '6') | ...
(NBIRecord(200)=='7')|(NBIRecord(200) == '8'))
%determine the STCNTY code
STCNTY = str2num (strcat(NBIRecord(1:2),NBIRecord(30:32))););
end
I cannot understand the if statement. Could any one help me with this. Thank You

Best Answer

  • The first if is completely superfluous; it might as well be removed as the test for EOF in the while loop will terminate the loop when the condition is true. That's an aside from the question raised, however...
    It's simply test whether the information in the record is that which is wanted...the character positions in the record 19, 374 and 200 are apparently codings for a given bridge classification and number and whoever wrote the particular code snippet was looking for a combination of whatever those two conditions in 19 and 374 are that are both a '1' and 'Y' and then under that one of the set of numbers 1 and 5 thru 8, inclusive. It's written this way since fgetl gets the record as a string so it's a character comparison.
    What it really "means" will be dependent upon what the codes are in the two positions 19 and 374, but the code is pretty straightforward.
    ADDENDUM
    A more "Matlaby" way would be to either read the full file and do the selection in memory which might improve performance noticeably if the file is large over the line-by-line reading above, trading i/o for memory altho once the unwanted rows are eliminated the final memory going forward will end up the same it's just a temporary allocation for the file at the beginning.
    The logic for the test could be simplified still using the string compare by defining a set of values for the numeric values sotoo:
    nos=['1' '5':'8']; % define the numbers in the keep list
    and then rewrite the if condition a little using it as
    if (NBIRecord(19)=='1') & (NBIRecord(374)=='Y') & ismember(NBIRecord(200),nos)
    This has the advantage that the set of bridge numbers wanted can be changed simply by defining the array pool and the logic statement is independent of the number of and content of the set.