Reading different lines with different numbers of data

1 回表示 (過去 30 日間)
Sanwar Ahmad
Sanwar Ahmad 2019 年 10 月 4 日
回答済み: Sanwar Ahmad 2019 年 10 月 4 日
Hi
I have the following file where the data are organised in the following way:
$Nodes
1 16 0 1
146
9.616887654983829 -2.74143608924586 3.7
1 17 0 4
147
148
149
150
9.736663950053746 2.27977523535189 4.38
9.736663950053746 2.27977523535189 5.06
9.736663950053746 2.27977523535189 5.74
9.736663950053746 2.27977523535189 6.42
$EndNodes
So, I want to read this filename.txt file, and store the data in a matrix of size (*, 3). The three numbers in bold will form the 3 columns in the matrix.
How can I do that? Thanks in Advance.
Sanwar

採用された回答

meghannmarie
meghannmarie 2019 年 10 月 4 日
This code is assuming that the only lines that have 3 fields is your data:
file = 'filename.txt';
fileID = fopen(file);
data = double.empty(0,3);
line_ex = 1;
while all(line_ex ~= -1)
line_ex = fgetl(fileID)
if ischar(line_ex)
line_ex = str2num(line_ex);
if size(line_ex,2) == 3
data(end + 1,:) = line_ex;
end
end
end
fclose(fileID);

その他の回答 (1 件)

Sanwar Ahmad
Sanwar Ahmad 2019 年 10 月 4 日
Thanks, meghannmarie! I just needed the following modification.
file = 'filename.txt';
fileID = fopen(file);
data = double.empty(0,3);
line_ex = 1;
while all(line_ex ~= -1)
line_ex = fgetl(fileID)
if ischar(line_ex)
line_ex = sscanf(line_ex,'%f');
if length(line_ex) == 3
% line_ex = str2num(line_ex);
% if size(line_ex,2) == 3
data(end + 1,:) = line_ex;
end
end
end
fclose(fileID);
Sanwar

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by