如何在 MATLAB 中将文本文件中的数据读入矩阵

发布于 2025-01-02 04:42:30 字数 235 浏览 2 评论 0原文

我无法将 .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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不忘初心 2025-01-09 04:42:30

从文本文件加载矩阵的最佳命令是 load 命令。具体来说,该文件必须满足以下条件:

  1. 第一行可以包含文本,但必须包含 % 作为第一个字符,否则它将不起作用。 % 充当注释值。
  2. 文件数据部分中的值必须采用矩阵格式,中间有分隔符。每行都是矩阵的一行。

因此,我可以读取这样的文件:

%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:

  1. The first lines can include text, but they must include a % as the first character, otherwise it will not work. The % acts as a comment value.
  2. The values in the data portion of the file must be in a matrix format, with a deliminator in between. Each row will be a row of the matrix.

So, I could read in a file like this:

%Q1 Q2 Q3
1 2 3
4 5 6
7 8 9

by simply calling a load command on the filename. IE, if it's called test.txt, I call blah=load('test.txt') The same command would read in the matrix you have included, or any arbitrary matrix.

Alternatively, you could look at reading one line in at a time, and searching for the end of the file. The command is fgetl.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文