如何循环文本文件并将该数据输入矩阵

时间:2017-12-01 01:08:45

标签: matlab loops for-loop matrix text-files

[MATLAB]

我有一个文本文件,它是一个数字列表。下面是一个示例,但我的实际文件是数千个值的列表,每个值都在一个新行上。

  

0.01080000000

     

0.00720000000

     

0.05760000000

     

0.00360000000

如何遍历此文本文件并将数据输入到x = 431和y = 415的矩阵中?同样,文本文件只有一个列表,所以我需要每隔431个数字转到矩阵中的新行。

clear;

%Load in text file
filename = 'Water_1973_points.txt';
T = fopen(filename);

%Count number of points in x,y (x = 431) (y = 415)
xsize = 431;
ysize = 415;

m=zeros(xsize, ysize);
tline = fgetl(T);
for k = 1:length(T)
    for h = 1:xsize
     for j = 1:ysize
         m(h,j) =  k*255;
     end
    end
end

1 个答案:

答案 0 :(得分:1)

如果您的文件很简单,只需使用importdatareshape即可。

例如,使用以下Water_1973_points.txt

1
2
...
10

m = importdata('Water_1973_points.txt');
m = reshape(m, 5, 2).';  % Transpose because MATLAB is column-major

返回:

m =

     1     2     3     4     5
     6     7     8     9    10
相关问题