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

data importfseekMATLABskip text in centre of numeric datatextscan

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!

Best Answer

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.