How to import data from the following txt file into MATLAB?
1 view (last 30 days)
Show older comments
Assume you have the txt file enclosed:
How to import only the data into MATLAB?
I have tried 'importdata', which also imports the strings into MATLAB. For instance, I use a1 = importdata('filename.txt'). Then in workspace, a1 reads as follows,
data < 1001*2 double >
textdata < 2*1 cell >
How can I extract only the data info and get rid of the textdata? Many thanks in advance!
0 Comments
Accepted Answer
Star Strider
on 15 Nov 2014
You have to do it in two steps with textscan, but it’s relatively straightforward:
fidi = fopen('S21.txt');
D1 = textscan(fidi, '%f %f', 'HeaderLines',2, 'Delimiter','\n', 'CollectOutput',1);
fseek(fidi,0,0); % Position Start Of Second Part Of File
D2 = textscan(fidi, '%f %f', 'HeaderLines',2, 'Delimiter','\n', 'CollectOutput',1);
You can verify the input with these optional lines that read the first five and last five lines of each section of the file:
D1{:}([1:5 end-4:end],:) % Diagnostic Look
D2{:}([1:5 end-4:end],:) % Diagnostic Look
This was an interesting problem! I’ve not needed to use fseek in a very long while, so this was educational for me, too. There are some NaN values at the end that you may want to get rid of (the isnan function is your friend here), but otherwise, everything is there.
0 Comments
More Answers (1)
QI
on 15 Nov 2014
1 Comment
Star Strider
on 15 Nov 2014
My pleasure! Cheers!
Just do isfinite on the data you read from the files and the NaN values disappear. You need do nothing else.
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!