How to read a file containing non numerical characters and commas?

1 view (last 30 days)
Dear all,
I need to read several files containing 22 rows of text at the beginning, and then two colunms containing decimals number, separated by commas (see file attached). The delimiter between the two column of data is a space.
The file attached is a .txt file converted only to insert it here, but i'm working with files without extension (ex: 'He_2').
I started with:
fid=fopen('He_2')
A=textscan(fid,'%s','Delimiter',' ');
data = strrep (A{1,1}, ',' , '.');
save('data_2','data') % saved as a .mat file, which is a cell containing a 1022x1 vector. I can't save it as data_2.txt here.
I would like to convert this into a matrix to use dlmread(matrixName,' ',22,0), but cell2mat doesn't work here (probably because of the 22 rows of text?).
Also, the code I'm using now only saves a cell containing the first column of interest, and I need at the end a 1000x2 matrix (I need the 2 columns of data I have in the original file, named "X_Value Untitled" and "Comment").
I hope I was clear,
Thank you in advance for your help!

Accepted Answer

Are Mjaavatten
Are Mjaavatten on 30 Jul 2019
The 22 lines of text are easily dealt with using the 'HeaderLines' option. Next you must convert your strings to doubles. Below, I have used sscanf to do this. For more numbers per line, just change the size of 'data'.
fid = fopen('He_2');
A=textscan(fid,'%s','Delimiter',' ','HeaderLines',22);
fclose(fid);
lines = strrep (A{1}, ',' , '.');
data = zeros(length(lines),2);
for i = 1:length(lines)
data(i,:) = sscanf(lines{i},'%f')';
end

More Answers (1)

Stephen23
Stephen23 on 30 Jul 2019
opt = {'HeaderLines',22,'MultipleDelimsAsOne',true};
str = fileread('He_2.txt');
str = strrep(str,',','.');
C = textscan(str,'%f%f',opt{:});
Giving:
>> M = [C{:}];
M =
0 0.000168
5e-09 3.0156e-05
1e-08 0.000112
1.5e-08 0.000158
2e-08 0.000174
2.5e-08 0.000169
3e-08 0.000178
3.5e-08 0.000165
4e-08 0.000185
4.5e-08 0.000172
... lots of lines here
4.9955e-05 0.000142
4.996e-05 0.000137
4.9965e-05 0.000151
4.997e-05 0.000153
4.9975e-05 0.000145
4.998e-05 0.000139
4.9985e-05 0.000142
4.999e-05 0.00015
4.9995e-05 0.000134

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!