Reading data row by row into matlab.

60 ビュー (過去 30 日間)
Jorge Guzman
Jorge Guzman 2019 年 2 月 21 日
コメント済み: Yasir Iqbal 2021 年 11 月 16 日
I need to read a text file, row by row, into different variables for the first 5 rows. Afterwards an N x M matrix needs to be read in. Is there a simple way to do this? I've tried to use textrfead, fopen, etc, but can't figure out how to get just the numbers I need.
this would be a sample file:
8
10
12 15 12 18 17 19 14 16
200 155 487 632 526 321 845 80
52 41 78 62 32 45 67 85 29 10 15
followed by a matrix of size 8 x10 (the matrix will always be size of the first two inputs)
Sorry, I uploaded two sample files. I know how to read in everything but the matrix at the end. That's what I need help retrieving from the files.
  2 件のコメント
Kevin Chng
Kevin Chng 2019 年 2 月 22 日
It is a bit confusing about
for the first 5 rows. After words an N x M matrix needs to be read in.
I guess you are only wanted to read certain line in your text file.
If you could upload your text file, and let us know which line you want to read, i can try to write the code for you here.
Jorge Guzman
Jorge Guzman 2019 年 3 月 29 日
I uploaded sample files. I can read everything except for line 6 onward as a matrix. I need to be able to read in different sized matrices.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2019 年 2 月 22 日
編集済み: Stephen23 2019 年 2 月 22 日
Why not just use dlmread ?:
>> M = dlmread('test.txt','',2,0)
M =
12 15 12 18 17 19 14 16 0 0 0
200 155 487 632 526 321 845 80 0 0 0
52 41 78 62 32 45 67 85 29 10 15
I had to create my own test file (attached) based on your description because you did not provide one. If you upload a sample file then it makes it easier for us to help you, and faster for you to get the results that you want.
  1 件のコメント
Jorge Guzman
Jorge Guzman 2019 年 3 月 29 日
Thank you, this works i just needed to offset by 5. since the matrix is found on the 6th line and onward!

サインインしてコメントする。

その他の回答 (1 件)

Are Mjaavatten
Are Mjaavatten 2019 年 2 月 22 日
I often find it useful to read the file into a cell array of strings using textscan. Then I can easily experiment with how to best parse each line. In your case, this resulted in:
fid = fopen(filename);
lines = textscan(fid,'%s','delimiter','\n');
fclose(fid);
lines = lines{1};
n = sscanf(lines{1},'%d');
m = sscanf(lines{2},'%d');
% parse lines 3-5
M = zeros(n,m);
for i = 1:n
M(i,:) = sscanf(lines{5+i},'%f')';
% Alternatively:
% M(i,:) = str2num(lines{5+i});
end
  1 件のコメント
Yasir Iqbal
Yasir Iqbal 2021 年 11 月 16 日
Brilliant

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by