如何在MATLAB中将文本文件中的数据读入矩阵(How to read data from a text file into a matrix in MATLAB)
我在将.txt文件读入单个矩阵时遇到困难,行和列显示在MATLAB的下面文本中。
%Q1 Q2 Q3 Q4 Q5
42 90 55 25 32
23 55 70 89 53
我将如何创建一个只有来自该文本文件的数字的单个矩阵? 值由空格分隔。 有19行,但我希望能够在发生更改时使用任意数量的行和列来读取它。 我尝试使用textscan和fscanf,但目前为止没有运气。 谢谢您的帮助。
I'm having difficulty reading my .txt file into a single matrix with the rows and columns show in the text below in MATLAB.
%Q1 Q2 Q3 Q4 Q5
42 90 55 25 32
23 55 70 89 53
How would I create a single matrix with only the numbers from that text file? The values are delimited by spaces. There are 19 rows, but I want to be able to read it with an arbitrary number of rows and columns in case of changes. I tried using textscan and fscanf but no luck so far. Thanks for the help.
原文:https://stackoverflow.com/questions/9148245
2020-03-01 16:43
满意答案
从文本文件load矩阵的最佳命令是load命令。 具体而言,该文件必须符合以下条件:
第一行可以包含文本,但必须包含%作为第一个字符,否则它将不起作用。 该%充当评论值。
文件数据部分中的值必须采用矩阵格式,中间有一个分隔符。 每行将是矩阵的一行。
所以,我可以读取像这样的文件:
%Q1 Q2 Q3
1 2 3
4 5 6
7 8 9
通过简单地调用文件名的加载命令。 IE,如果它被称为test.txt,我称之为blah=load('test.txt')同样的命令会读入你包含的矩阵或者任意的矩阵。
或者,您可以查看一次读取一行,并搜索文件的结尾。 该命令是fgetl 。
The best command to load in a matrix from a text file is the load command. Specifically, the file must meet the following criteria:
The first lines can include text, but they must include a % as the first character, otherwise it will not