How to import data from the following txt file into MATLAB?

1 view (last 30 days)
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!

Accepted Answer

Star Strider
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.

More Answers (1)

QI
QI on 15 Nov 2014
Thanks, mate! Really helpful!
The data file was exported from a simulation software directly. With your help, I do not have remove the headers manually.
The NaN values at the end should come from the bottom 'empty' lines. I can then overcome them by reading the useful data (lines) since the format of the exported file is consistent under every header.
Cheers!
  1 Comment
Star Strider
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.

Sign in to comment.

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!