I want TEXTSCAN to be able to consider spaces in front of numbers

1 次查看(过去 30 天)
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

回答(2 个)

Star Strider
Star Strider 2016-10-21
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.

Guillaume
Guillaume 2016-10-21
编辑:Guillaume 2016-10-21
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by