Read .txt and Write in matab
Show older comments
Hi
i have 30000 thousand line of input file in text file, but i only need line 2618-3400.
imposible if i have to write manual to the end
how to write value C that consist of data from 2618-3400
A=readfile('data.txt')';
%line 2618 to 3484
C =[A{2618,1} A{2619,1} A{2620,1} A{2621,1} A{2622,1} A{2623,1} A{2624,1}]
format long g
pf = sscanf(C,'%f')
7 Comments
Ajay Kumar
on 11 Nov 2019
uploading data.txt would be helpful
vaya putra
on 11 Nov 2019
Adam Danz
on 11 Nov 2019
I'm unfamiliar with readfile() (FEX submission) but I read the description and it appears to be a fileread() wrapper with some enhancements.
Why don't you use either function to just read in the entire file and the extract the rows you need? That would take 2 lines of code and it's pretty fast.
vaya putra
on 11 Nov 2019
"i have no idea with fileread(),"
It's really easy to read in the entire file. You literally just provide the filename. Once you've read in the entire file, then you just use indexing to extract the rows you want.
vaya putra
on 11 Nov 2019
Accepted Answer
More Answers (1)
Adam Danz
on 11 Nov 2019
Read in the whole file at once. In this example I'm using fileread() because I'm unfamiliar with the FEX submission readfile() mentioned in your question.
C = fileread('myTextFile.txt');
Split the char array by lines into a cell array
Ca = strsplit(C,newline);
Extract text lines n to m
Ca(n:m)
If you'd rather have a char array as output
char(Ca(n:m))
3 Comments
Rik
on 12 Nov 2019
It doesn't seem to matter for this specific file (especially for the numerical data part), but the fileread function ignores the encoding, which results in the wrong output for any char >255. Which is why I wrote this submission in the first place (and because many methods of file reading throw away blank lines).
Adam Danz
on 13 Nov 2019
I just had the chance to check out that function. I see why it would be useful!
Rik
on 13 Nov 2019
You can probably imagine the frustration that led to me writing this function. I admit it is a strange use case to want a text file reader that handles UTF8 and ANSI for both Matlab and Octave. I even managed to find a bug in the Octave implemention of textscan.
If you have any suggestions for how to make the function more robust, please feel free to comment on the FEX (or send me an email, you can get the address from the function doc).
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!