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

2 次查看(过去 30 天)
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!

采纳的回答

Star Strider
Star Strider 2014-11-15
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.

更多回答(1 个)

QI
QI 2014-11-15
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 个评论
Star Strider
Star Strider 2014-11-15
My pleasure! Cheers!
Just do isfinite on the data you read from the files and the NaN values disappear. You need do nothing else.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by