I want TEXTSCAN to be able to consider spaces in front of numbers
1 view (last 30 days)
Show older comments
Dear all,
Hello, I have a problem to read one text file made by Fortran.
This file has two columns: first one is Julian days (1~365) and second one is precipitation.
This file was made by Fortran and the used format was "format(i5,f7.2)".
Therefore, my file has spaces in front of Julian days to make up the 5 field width.
Usually, there's no problem to extract each of them, but when precipitation data is huge then it becomes difficult because there's no space between first and second columns.
For example, 'Julian day', 'Precipitation'
1 0.00
2 10.00
31300.00
.
.
3651000.00
In day 3 (precipitation:1300) and 365 (precipitation:1000), you can find no spaces there.
I used code below to read the file and got the result followed.
pf = textscan(fid,'%3d%7.2f');
Result is
pf{1,1}=1;2;313;...;365
pf{2,1}=0;10;0;...;1000
How can I get the result below?
Desired result is
pf{1,1}=1;2;3;...;365
pf{2,1}=0;10;1300;...;1000
Thank you for reading!
Sincerely, M
0 Comments
Answers (2)
Star Strider
on 21 Oct 2016
You probably need to use fgets or fgetl and use vector addressing to separate the fields. MATLAB cannot emulate FORTRAN format descriptors that would allow you to do that with textscan or any other high-level file import function.
0 Comments
Guillaume
on 21 Oct 2016
Edited: Guillaume
on 21 Oct 2016
Yes, as Star says you probably have to go at a lower level than text scan. In this case, this is what I would do:
wholefilecontent = fileread('fullpathtothefile'); %read the whole file in one go
filelines = strsplit(wholefilecontent, {'\n', '\r'}); %works for both linux and windows line ending.
filefields = cellfun(@(line) {line(1:3), line(4:10)}, filelines, 'UniformOutput', false); %split each line into 3-7 strings
filevalues = str2double(vertcat(filefields{:})) %convert the whole lot at once
0 Comments
See Also
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!