首页 > 解决方案 > 如何读取文本文件中所需的行范围并将这些范围的元素分配给 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

标签: matlabfilematrix

解决方案


这就是我解决问题的方法:

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)

推荐阅读