matlab - 如何读取文本文件中所需的行范围并将这些范围的元素分配给 MATLAB 中的不同矩阵?
问题描述
我有一个包含一些元素的文本文件:
5
4
4 3 1 4
3 1 2 1
9 8 1 3
4 Inf Inf 4
13 9 Inf 6
1 3
2 3
3 4
4 5
-1 -1
我需要用这些元素创建 2 个不同的矩阵。前两行中的前两个元素(此处为 5 和 4)对应于第一个矩阵(在此示例中为 5x4 矩阵)的大小 (mxn)。我应该将下面的 mxn 元素(从第 2 行到第 5 行,这里总共 20 个元素)分配到一个矩阵中。之后,应将直到最后一行(具有 -1 -1)的剩余值分配给另一个 pxt 矩阵(在此示例中,一个 4x2 矩阵。具有 -1 -1 的行表示行的结尾。)
我将使用许多文本文件,它们的行数和列数彼此不同(应该创建的矩阵的大小不同。),所以我需要编写可以运行所有文本文件的代码。我试图写一段代码,但它的结果是错误的,因为值之间有空格,程序假设这些空格是字符。此外,13 和 Inf 有多个字符。这是我的代码和第一个矩阵的结果。另外,我需要像我解释的那样创建第二个矩阵,但我不知道该怎么做。
clear;
clc;
fileID=fopen('1.txt', 'r');
nrow = fscanf(fileID,'%d',1);
ncolumn = fscanf(fileID,'%d',1);
maxrix1 = zeros(nrow,ncolumn);
a = 1;
nline = 1;
while ~feof(fileID) && nline<nrow+2
line = fgetl(fileID);
if(nline > 1 && nline<=nrow+2)
for b = 1:ncolumn
if ~ischar(line), break, end
maxrix1(a, b) = str2double(line(b));
end
a = a + 1;
end
nline = nline + 1;
end
fclose(fileID);
这是我收到的结果,但这不是真的,因为空格和元素不止一个字符(Inf 和 13)
4 NaN 3 NaN
3 NaN 1 NaN
9 NaN 8 NaN
4 NaN NaN NaN
1 3 NaN 9
它应该是:
4 3 1 4
3 1 2 1
9 8 1 3
4 Inf Inf 4
13 9 Inf 6
更正创建matrix1的代码后,我需要像这样创建matrix2:
1 3
2 3
3 4
4 5
解决方案
这就是我解决问题的方法:
fid = fopen('file.txt');
M = str2double(fgetl(fid));
N = str2double(fgetl(fid));
matrix1 = NaN(M,N); % initiallize and preallocate
for m = 1:M
li = fgetl(fid); % read next line
matrix1(m,:) = str2double(strsplit(li, ' ')); % avoid str2num
end
matrix2 = []; % initiallize. We cannot preallocate
while true % we will exit explicitly with a break statement
li = fgetl(fid); % read next line. Gives -1 if end of file
if ~isequal(li, -1)
matrix2(end+1,:) = str2double(strsplit(li, ' ')); % avoid str2num
else
break
end
end
matrix2(end,:) = []; % remove last row, which contains [-1 -1]
fclose(fid)
推荐阅读
- css - 有没有办法直接在类属性中使用 bootstrap 5 自定义颜色?
- python-3.x - 在 Python 中实现链表
- javascript - 我只想在模型查看器中播放带有音频的动画
- nlp - 使用 Huggingface TextClassificationPipeline 时如何设置标签名称?
- django - Djanog 在主模型和连接模型中以一对多的关系在其余 API 上发布数据
- reactjs - 如何在 react-table 单元格中实现 react-markdown?
- javascript - 为什么这个 XOR 加密不起作用?我正在尝试传递一些值,但它不起作用
- excel - 在 Excel 中选择要通过电子邮件发送的范围时需要 VBA 运行时错误 424 对象
- r - 在 R studio (ggplot, facet_wrap) 上创建折线图的插图
- java - 计算非二叉树的元素个数