我正在尝试将包含数据的.txt文件加载到Matlab,以用于某些计算。但是,当我运行代码时,变量/数组返回为空或空白。 下面有我正在使用的代码。
%% importing the data
% Open file in the memory
fileID = fopen('rainfall.txt');
% Read the txt file with formats: Integer, Integer, Float
% Treat multiple delimiters, which is "space" in here, as one. Put the data
% in a variable called chunk.
chunk = textscan(fileID,'%d %d %f','Delimiter',' ',...
'MultipleDelimsAsOne',1);
% Close file from the memory.
fclose(fileID);
% date
dt = chunk{:,1};
% hour
hr = chunk{:,2};
% precip
r = chunk{:,3};
% remove extra variables from Matlab workspace
clear fileID ans
在Matlab的“工作区”选项卡中,它显示chunk
为空的1x3 cell
。这将导致dt,hr和r都不具有任何值,并被列为具有[]
的值。因此,我最好的猜测是,将数据加载到Matlab中出了问题。
此外,这是我正在使用的数据的一小部分。这也正是将其写入.txt文件的方式。
STATION DATE HPCP
----------------- -------------- --------
COOP:132367 20040116 22:00 0.01
COOP:132367 20040116 23:00 0.01
COOP:132367 20040117 00:00 0.04
COOP:132367 20040117 01:00 0.02
COOP:132367 20040117 02:00 0.00
在实际文件中,我的数据比这里列出的要多得多,但这应该使您了解数据的外观以及格式。
答案 0 :(得分:2)
textscan尝试将文件中的数据与formatSpec中的转换说明符进行匹配。 textscan函数在整个文件中重新应用formatSpec,并在无法将formatSpec与数据匹配时停止。
第一个问题是标题行。您应该丢弃它们。例如,通过手动读取2行(使用fgetl
)。
接下来,您应确保格式与数据匹配。您尝试读取2个整数和一个浮点数,但您也拥有电台名称。
我认为以下应该可以:
fileID = fopen('rainfall.txt');
l = fgetl(fileID);
l = fgetl(fileID);
chunk = textscan(fileID,'%s:%d %d %d %f','Delimiter',' ',...
'MultipleDelimsAsOne',1);