textscan and fscanf for text with some rows only text and some rows only numbers
12 views (last 30 days)
Show older comments
>> matrix=[1:4;4:7]
matrix =
1 2 3 4
4 5 6 7
>> save onematrix.reef matrix -ascii
>> fid=fopen('onematrix.reef', 'a')
fid =
4
>> fprintf(fid,'a jeep\n in %s', 'Egypt')
ans =
16
>> fclose(fid)
ans =
0
>> fid=fopen('onematrix.reef','r')
fid =
4
>> while ~feof(fid)
fgetl(fid)
end
ans =
1.0000000e+000 2.0000000e+000 3.0000000e+000 4.0000000e+000
ans =
4.0000000e+000 5.0000000e+000 6.0000000e+000 7.0000000e+000
ans =
a jeep
ans =
in Egypt
>>
I opened the file above with fgetl but I wondered if I could open it with textscan or fscanf even though the lines had no common system of words and numbers like
a 3 c
b 22 e
r 678 g
is it possible?
1 Comment
Walter Roberson
on 18 Nov 2011
Do you want all the numbers read, even if they occur on lines with text, or do you want to skip everything on a line that has text in it (other than the 'e', '.', '+' and '-' of the fixed-point format) ?
Answers (1)
Fangjun Jiang
on 19 Nov 2011
If the numerical data and text strings are in two separate chunks, like the file 'onematrix.reef' you created, function importdata() or uiimport() should be able to read it.
If the mixing pattern of numerical data and text strings are consistent, like the example data at the end of your question, textscan() should be able to handle it.
If there is no consistent pattern, you best shot is to read in the whole contents and then use regexp() to process it.
0 Comments
See Also
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!