Is there a way to recognize blank lines in matlab?

Is there a way to recognize blank lines when scanning a text file in Matlab? I want to parse files based on empty lines between text. Is it possible?

+5
source share
3 answers

Yes it is possible. A MATLAB fragment will look something like this:

fid = fopen('reader.m');

newline = sprintf('\r\n');
line = fgets(fid);
while ischar(line)
    if strcmp(newline, line)
        disp('Empty line');
    else
        disp('Non-empty line');
    end
    line = fgets(fid);
end
+2
source

Here is one possibility:

fid = fopen('myfile.txt');
lines = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
lines = lines{1};
% lines now contains a cell array of strings,
% one per line in the file.

% Find all the blank lines using cellfun:
blank_lines = find(cellfun('isempty', lines));
+2
source

without \ r ... now works great

fid = fopen('reader.m');

newline = sprintf('\n');
line = fgets(fid);
while ischar(line)
    if strcmp(newline, line)
        disp('Empty line');
    else
        disp('Non-empty line');
    end
    line = fgets(fid);
end
0
source

All Articles