首页 > 解决方案 > 将 .txt 文件上传到 Matlab 时取回空数组/变量

问题描述

我正在尝试将带有数据的 .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 的 Workspace 选项卡中,它显示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  

在实际文件中,我的数据比我在此处列出的要多得多,但这应该可以让您了解数据的外观和格式。

标签: arraysmatlabvariablesfile-uploadtext-files

解决方案


textscan 帮助页面

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);

推荐阅读