フィルターのクリア

How to create a matrix from a txt file with variable column numbers?

1 回表示 (過去 30 日間)
Diogo Nascimento
Diogo Nascimento 2016 年 4 月 11 日
コメント済み: Diogo Nascimento 2016 年 4 月 12 日
Hey there!
I am trying to create a matrix from a txt file that the user inputs that goes like this:
Matrix
4
1 1 3 2 6 1
2 1 4 3 5 2 5
3 1 3 4 8 3
4 1 3 5 1 6
The number in the line after "Matrix" represents the number of lines of the matrix I wanna create.
The number of the 3rd column represent the remaining entries on that line and can only vary between 3 or 4.
I've come up with
tline = fgetl(file);
n = fscanf(file,'%f',1);
matrix = fscanf(file,'%e', [n inf]); % but this puts it into a 1x... Matrix...
Thanks for the help
  2 件のコメント
Jan
Jan 2016 年 4 月 11 日
What result do you want? A matrix is rectangular by definition.
Diogo Nascimento
Diogo Nascimento 2016 年 4 月 12 日
I want to fill the shorter rows with zero, to make it rectangular

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

採用された回答

Walter Roberson
Walter Roberson 2016 年 4 月 12 日
tline = fgetl(file);
n = fscanf(file, '%f', 1);
for K = 1 : n
rownum = fscanf(file, '%f', 1);
col_offset = fscanf(file, '%f', 1);
num_ent = fscanf(file, '%f');
data_for_row = fscanf(file, '%f', [1 num_ent]);
data(rownum, col_offset + (0:num_ent-1)) = data_for_row;
end
This will pad shorter rows with 0. I had to guess at the meaning of the fields.
  3 件のコメント
Walter Roberson
Walter Roberson 2016 年 4 月 12 日
Change
num_ent = fscanf(file, '%f');
to
num_ent = fscanf(file, '%f', 1);
Diogo Nascimento
Diogo Nascimento 2016 年 4 月 12 日
thank you so much! that did the trick!
just had to adjust
data(rownum, col_offset + (0:num_ent-1)) = data_for_row;
to
data(rownum, (1:num_ent)) = data_for_row;
and it worked for other matrixs!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by