简体   繁体   English

Matlab:将多个数字csv .txt文件导入单个单元格数组

[英]Matlab: Import multiple numeric csv .txt files into single cell array

I have multiple (say N of them) .txt files consisting of numeric csv data in matrix form. 我有多个(例如N个).txt文件,这些文件由矩阵形式的数字csv数据组成。 I would like to import each of these data files into one (1 x N) cell array, whilst preserving the original matrix form. 我想将每个数据文件导入一个(1 x N)单元格数组,同时保留原始矩阵形式。 If the original data is small, say 3x3, then textscan does the job in the following manner: 如果原始数据很小,例如3x3,则textscan以以下方式执行此工作:

fileId = fopen('data1.txt');
A{1} = textscan(fileID, '%d %d %d', 'delimiter',',','CollectOutput',1);

(This will be part of a function.) But what if my .txt files have 100 columns of data? (这将是功能的一部分。)但是,如果我的.txt文件具有100列数据怎么办? I could write '%d' 100 times in the formatSpec, but there must be a better way? 我可以在formatSpec中写'%d'100次,但是必须有更好的方法吗?

This seems to be an easy problem, but I'm quite new to Matlab and am at a loss as to how to proceed. 这似乎是一个简单的问题,但是我对Matlab还是很陌生,并且对如何进行操作一无所知。 Any advice would be much appreciated, thanks!! 任何建议将不胜感激,谢谢!

For such cases with consistent data in each of those text files, you can use importdata without worrying about format specifiers. 对于这些文本文件中的每个文件中具有一致数据的情况,可以使用importdata而不用担心格式说明符。 Two approaches are discussed here based on it. 在此基础上讨论了两种方法。

Approach 1 方法1

filenames = {'data1.txt' 'data2.txt' 'data3.txt'}; %// cell array of filenames
A = cell(1,numel(filenames)); %// Pre-allocation
for k = 1:numel(filenames)
    imported_data = importdata(char(filenames(k)));
    formatted_data = cellfun(@str2num, imported_data, 'uni', 0);
    A{k} = vertcat(formatted_data{:})
end

Approach 2 方法2

Assuming those text files are the only .txt files in the current working directory, you can directly get the filenames and use them to store data from them into a cell array, like this - 假设这些文本文件是当前工作目录中仅有的.txt文件,则可以直接获取文件名,并使用它们将数据从文件名存储到单元格数组中,如下所示-

files = dir('*.txt');
A = cell(1,numel(files)); %// Pre-allocation
for k = 1:numel(files)
    imported_data = importdata(files(k).name);
    formatted_data = cellfun(@str2num, imported_data, 'uni', 0)
    A{k} = vertcat(formatted_data{:})
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM