如何在 MATLAB 中从文本文件创建矩阵?
我有一个包含 4 列的文本文件,每列有 65536 个数据点。 行中的每个元素都用逗号分隔。 例如:
X,Y,Z,AU
4010.0,3210.0,-440.0,0.0
4010.0,3210.0,-420.0,0.0
etc.
所以,我有 65536 行,每行有 4 个数据值,如上所示。 我想把它转换成矩阵。 我尝试将数据从文本文件导入到Excel文件中,因为这样很容易创建矩阵,但我丢失了一半以上的数据。
I have a text file which has 4 columns, each column having 65536 data points. Every element in the row is separated by a comma. For example:
X,Y,Z,AU
4010.0,3210.0,-440.0,0.0
4010.0,3210.0,-420.0,0.0
etc.
So, I have 65536 rows, each row having 4 data values as shown above. I want to convert it into a matrix. I tried importing data from the text file to an excel file, because that way its easy to create a matrix, but I lost more than half the data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果文件中的所有条目都是数字,则只需使用
a = load('file.txt')
。 它应该创建一个 65536x4 矩阵a
。 它甚至比csvread
更容易If all the entries in your file are numeric, you can simply use
a = load('file.txt')
. It should create a 65536x4 matrixa
. It is even easier thancsvread
您是否尝试过使用“导入数据”?
您只需要文件名和分隔符的参数。
Have you ever tried using 'importdata'?
The parameters you need only file name and delimiter.
您应该能够将文本文件直接读入 MATLAB(使用函数 FOPEN,FGETL,FSCANF 和 FCLOSE):
Instead of messing with Excel, you should be able to read the text file directly into MATLAB (using the functions FOPEN, FGETL, FSCANF, and FCLOSE):
最简单的方法是使用 MATLAB 的
csvread
函数。还有此工具可以读取 CSV 文件。
您也可以自己完成,没有太大困难:只需循环文件中的每一行,然后用逗号将其分割,然后将其放入数组中。
The easiest way to do it would be to use MATLAB's
csvread
function.There is also this tool which reads CSV files.
You could do it yourself without too much difficulty either: Just loop over each line in the file and split it on commas and put it in your array.
建议您熟悉
dlmread
和textscan
。dlmread
类似于csvread
,但因为它可以处理任何分隔符(制表符、空格等),所以我倾向于使用它而不是csvread
。textscan
是真正的主力:有很多选项,+它适用于打开的文件,并且对于处理“坏”输入(例如文件中的非数字数据)更加稳健。 它可以像 gnovice 的建议中的fscanf
一样使用,但我认为它更快(不过不要引用我的话)。Suggest you familiarize yourself with
dlmread
andtextscan
.dlmread
is likecsvread
but because it can handle any delimiter (tab, space, etc), I tend to use it rather thancsvread
.textscan
is the real workhorse: lots of options, + it works on open files and is a little more robust to handling "bad" input (e.g. non-numeric data in the file). It can be used likefscanf
in gnovice's suggestion, but I think it is faster (don't quote me on that though).