gpt4 book ai didi

matlab - 条件文本导入或按 header 名称导入 - MATLAB

转载 作者:行者123 更新时间:2023-12-02 03:22:52 25 4
gpt4 key购买 nike

有没有办法在 MATLAB 中执行条件文本导入?例如使用制表符分隔的 .txt 文件,格式如下:

Type    A   B   C   D   E
A 5000 2 5 16 19
A 5000 3 4 5 4
A 5000 4 1 4 5
B 500 19 8 2 7
B 500 18 9 8 1
B 500 2 9 13 2
B 100 3 10 15 9
B 5000 4 15 14 10

有没有一种方法可以只导入 A 列包含“5000”的那些行?

这比导入整个 .txt 文件并在之后分离数据要优先,因为实际上,我的文本文件相当大(每个大约 200MB)——但如果有一种方法可以快速完成此操作,那也是一个合适的解决方案。

或者,是否有一种方法(类似于 R)可以使用 .txt 文件中包含的 header 导入和处理数据?例如在上面的示例中导入 'Type' 'A' 'B' 和 'D' 而忽略 'C' 和 'E'。如果输入文件格式灵活,有时添加额外的列意味着它们的相对位置发生变化,则需要这样做。

最佳答案

您可以尝试逐行读取输入文件,检查该行是否在引用列(本例中为第 2 列)中包含引用值(本例中为 5000)。

如果是这样,您可以存储输入,否则,您将丢弃它。

在下面的代码中,根据您的模板,您可以在代码的开头定义引用值和引用列。

然后您可以将 cellarray 输出转换为 array

% Define the column index
col_idx=2
% Define the reference value
ref_value=5000
% Open input file
fid=fopen('in.txt');
% Read header
tline = fgetl(fid);
% Initialize conter
cnt=0;
% Initialize output variable
data=[];
% Read the file line by line
while 1
% Read the line
tline = fgetl(fid);
% Check for the end of file
if ~ischar(tline)
break
end
% Get the line field
c=textscan(tline,'%c%f%f%f%f%f')
% If the seconf field contains the ref value, then store the inout data
if(c{col_idx} == ref_value)
data=[data;c]
end
end
fclose(fid);
% Convert cell 2 array
c=data(:,2:end)
num_data=cell2mat(c)
% Convert first column to char
lab=char(data(:,1))

希望这对您有所帮助。

关于matlab - 条件文本导入或按 header 名称导入 - MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com