MATLAB Answers

Billy
0

Read text file - ignoring lines starting with specific character.

Billy
さんによって質問されました 2019 年 10 月 1 日
最新アクティビティ Stephen Cobeldick
さんによって 回答されました 2019 年 10 月 1 日
I have a text file with 17 columns of numeric data separated by a double space. These are preceded by some number of lines starting with the '#' symbol. I would like to discard all lines starting with '#' and only read the numeric data, but these numbers need to be read in as strings. How do I ignore all lines starting with '#' and only read the remaining lines as strings?
The text file is of the form (but with more columns):
# filename
# date and time
# some more info
1.111111111 2.222222222 3.333333333 4.444444444 ...
1.111111112 2.222222223 3.333333334 4.444444445 ...

  0 件のコメント

サインイン to comment.

製品


リリース

R2019a

2 件の回答

Jon
Answer by Jon
on 1 Oct 2019
Edited by Jon
on 1 Oct 2019

I'm not sure why you would want to read in numerical data as strings.
You can read in the data in your files using (assuming for example your file is called myfile.csv)
A = readmatrix('myfile.csv','Delimiter',' ')
note that you seem to have two spaces between your values so it is ' ', not ' ' as the delimiter.
If you really want them to be strings, you can alway change them into strings after you read them in as numbers, using for instance
Astr = num2str(A)
If for some reason readmatrix is confused about some of the initial header lines (the ones you shouw starting with #, if you know how many header lines you can also specify that for example, for 3 header lines as you show in your listing
A = readmatrix('myfile.csv','Delimiter,' ',NumHeaderLines',3)

  0 件のコメント

サインイン to comment.


Stephen Cobeldick
Answer by Stephen Cobeldick on 1 Oct 2019

nmc = 4; % number of columns in file
fmt = repmat('%f',1,nmc);
opt = {'HeaderLines',3, 'CollectOutput',true, 'MultipleDelimsAsOne',true};
%
[fid,msg] = fopen('test.txt','rt');
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
M = C{1}
giving:
M =
1.111111111000000 2.222222222000000 3.333333333000000 4.444444444000000
1.111111112000000 2.222222223000000 3.333333334000000 4.444444445000000

  0 件のコメント

サインイン to comment.



Translated by