How to read text file which has blanks in some columns ?
Show older comments
I have a text file in the following format :
Algorithm SNR Q
A 20 30
25 32
30 35
B 20 32
25 34
30 36
I want to read this data of SNR and Q for 2 different algorithms so that i can plot SNR vs Q graph.
But the problem is that when I read this text file using Matlab functions (example textscan) , it doesn't read it correctly due to the empty spaces present in this text file in the column 'Algorithm'. For example: I tried to open this text file and read it and then display its contents :
fid = fopen('Test.txt');
C = textscan(fid,'%s %d %f');
fclose(fid);
celldisp(C);
The output of the above code is :
C{1}{1} = Algorithm
C{2} = []
C{3} = []
If I remove the first column named 'Algorithm' from the text file and then read that file, then it works fine. But I am unable to read it correctly when that String column is also present. Can anyone please help me to know how can I read such data correctly from a text file. Thanks for your help in advance.
Accepted Answer
More Answers (1)
per isakson
on 10 Jul 2013
Edited: per isakson
on 12 Jul 2013
Comments
- If you are in control of the program, which produces this text file, you could write the algorithm-value 'A' or 'B' on every line.
- The file as is can be read with a loop
while not( feof(fid) )
str = fgetl( fid )
parse str
end
.
In response to comment
My fault; I was too terse.
- parse str was intended as a hint (pseudo-code) and that you should replace it by real code. "as is" refers to the file you show in OP. Cedric provided a working code according to this approach.
- "'A' or 'B' on every line": My point is that one should write files that are easy to read. (There is a trade-off between easy to read for human and easy to read by a program.)
Here is an example of reading your modified file
>> cac = cssm()
cac =
{5x1 cell} [5x1 double] [5x1 double]
>> cac{1}
ans =
'Algo-A'
'Algo-A'
'Algo-B'
'Algo-B'
'Algo-B'
>> cac{2}
ans =
3
4
5
6
7
>> cac{3}
ans =
16.1200
20.1200
25.1200
31.1200
38.1200
>>
where
function cac = cssm()
fid = fopen( 'cssm.txt' );
cac = textscan( fid, '%s%f%f', 'Headerlines', 1 );
fclose( fid );
end
Categories
Find more on Text Data Preparation 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!