MATLAB Answers

Converting a text file into strings and integers

69 views (last 30 days)
I have .txt input files with a very simple structure, of which I attach an example. I want to convert its content in strings and integers. My code below works, but I was wondering if there is a faster option than "textread", which seems to be the weak point.
[pattern, text, d] = textread('dataset.txt', '%s %s %d');
pattern = cell2mat(pattern(1));
text = cell2mat(text(1));

  2 Comments

Paolo Binetti
Paolo Binetti on 19 Dec 2016
that textread is not recommended, but it does not say why and textscan does not seem to work in the same way. I have actually tried implementing textscan but I did not figure it out. Amazing how much time one can lose with I/O ...

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 19 Dec 2016
Is there only the one set of values for each file? If so then probably a few fscanf() would be faster.

  3 Comments

Paolo Binetti
Paolo Binetti on 19 Dec 2016
Thank you but I am not sure I understand your question. I have attached a file example. That is exactly the file I want to read (except that the string on the second row would be much longer).
Walter Roberson
Walter Roberson on 20 Dec 2016
fid = fopen('dataset.txt');
pattern = fscanf(fid, '%s', 1);
txt = fscanf(fid, '%s', 1);
d = fscanf(fid, '%f', 1);
fclose(fid);
Paolo Binetti
Paolo Binetti on 21 Dec 2016
Thank you: 5 times faster on my sample, noticeably faster on larger files, no longer the slowest piece of code in my algorithm.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags

No tags entered yet.