读取多个文本文件并将每个文本文件导入为列 [英] Read multiple text files and import each of them as columns

查看:106
本文介绍了读取多个文本文件并将每个文本文件导入为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,但我不知道如何将每个文本文件作为矩阵中的不同列放置.

I have a code but I have no idea how to get each of the text files to be placed as different columns in a matrix.

例如,我有5个文本文件,并且所有文件都只有一列.如何将它们的每一列合并到一个矩阵中?我写的代码在下面,但不起作用:

For example, I have 5 text files and all of them have only one column. How can I get each of their columns into a single matrix? The code I wrote is below but it isn't working:

for k = 1:5
 textFilename = ['file' num2str(k) '.txt'];
 fid = fopen(textFilename, 'rt');
 textData = fread(fid);
 fclose(fid);
end

推荐答案

我假设从所有文本文件读取的数据长度相同.如果是这种情况,那么您要做的就是创建一个空矩阵,然后将结果逐列连接.您只需添加两行.

I am assuming that the data read in from all of the text files are the same length. If that's the case, then all you have to do is create an empty matrix, then concatenate your results column by column. You simply have to add two lines.

 % Store the text data here
 textDataMatrix = [];
 for k = 1:5
  textFilename = ['file' num2str(k) '.txt'];
  fid = fopen(textFilename, 'rt');
  textData = fread(fid);
  % Concatenate text file data by column
  textDataMatrix = [textDataMatrix textData];
  fclose(fid);
 end

在此脚本的结尾,textDataMatrix将包含所需的文本数据,并根据需要放置在单独的列中.

At the end of this script, textDataMatrix will contain the text data that you wanted and placed in separate columns as you desired.

注意:通常,创建空矩阵并填充后的项目通常是较差的做法,因为它被认为很慢.如果您在运行此代码之前实际知道单个数据文件中有多少个字符/字节/数字,这将有所帮助.执行此操作时,可以在运行for循环之前预先分配所需数量的内存.在MATLAB中创建矩阵之前创建适当数量的空间比连接元素更有效.如果要用这种方法,请假设数据文件中的元素数称为numElements.您将通过以下方式重写我上面编写的代码:

NB: It is usually poor practice to create an empty matrix and populate your items after as it is considered slow. It will help if you actually know how many characters / bytes / numbers are in a single data file before running this code. When you do that, you can preallocate the right amount of memory you need before you run through the for loop. Creating the right amount of space before populating the matrix is more efficient in MATLAB instead of concatenating elements. If you want to do it this way, suppose that the number of elements you have in a data file is called numElements. You would rewrite the code I wrote above in the following way:

 % Store the text data here
 textDataMatrix = zeros(numElements, 5);
 for k = 1:5
  textFilename = ['file' num2str(k) '.txt'];
  fid = fopen(textFilename, 'rt');
  textData = fread(fid);
  % Place the k'th text data in the k'th column
  textDataMatrix(:,k) = textData;
  fclose(fid);
 end

但是,如果特定文本文件中没有那么多元素,那么上面的代码的第一个版本就可以了.

However, if there aren't that many elements in a particular text file, then the first version of the code I have above will be just fine.

这篇关于读取多个文本文件并将每个文本文件导入为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆