MATLAB Answers

reading a .txt

1 view (last 30 days)
nono
nono on 11 Oct 2016
Edited: Thorsten on 20 Oct 2016
Dear Everyone, I am really embarrased, and I m pretty sure my problem is simple... I have a txt file with 2 columns of float numbers seperated with a tabulation. Above and below those two columns there are informations that might be interesting. First of all I d like to proceed to the acquisition of the 2 columns, ONLY. Secondly I'd like to get the value of some other informations like "resolution" (at the end of the file) value which is 20.00 here. Please find attached the text file. Best regards and thank you very much for your help :-)
  2 Comments
Walter Roberson
Walter Roberson on 11 Oct 2016
Technically that file is a binary file. There are no empty lines in the file, but each line ends in \r\r\n . Text files can have their lines ending in \r\n or \n but not \r\r\n .
That said, if you fopen() with 'rt' permissions, then MATLAB will treat the \r\r\n as a single end-of-line.

Sign in to comment.

Answers (2)

Jean-Marie Sainthillier
Jean-Marie Sainthillier on 20 Oct 2016
Edited: Jean-Marie Sainthillier on 20 Oct 2016
Try something like:
function M=read_X()
fid=fopen('01.txt');
fgetl(fid); % YOKO
fgetl(fid); % START
M=[];
temp=fgetl(fid);
while ~isequal(temp,'STOP')
temp=fgetl(fid);
if ~isempty(temp)
M=[M ;str2num(temp)];
end
end
fclose(fid);

Thorsten
Thorsten on 20 Oct 2016
Edited: Thorsten on 20 Oct 2016
First check if the encoding is ISO-8859-1, such that accents are read correctly:
if ~strcmp(feature('DefaultCharacterSet'), 'ISO-8859-1')
feature('DefaultCharacterSet', 'ISO-8859-1')
end
X = textread('01.txt', '%s');
ind = find(strcmp(X, 'START')):find(strcmp(X, 'STOP'));
ind = ind(2:end-1); % numbers between START and STOP
Data = cellfun(@(x) sscanf(x, '%f'), X(ind));
Data = reshape(Data, 2, [])';
ind = find(strcmp(X, 'Résolution')) + 2;
resolution = sscanf(X{ind}, '%f');

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by