How to read a specific row in a txt-file with variable row length?

2 views (last 30 days)
Dear Matlab users,
Maybe someone can help me with the following:
For a project I would like to read a certain row of the txt-file constant_file_matlab.txt. In this example I would like to read the 17th row:
n=7
M = dlmread('constant_file_matlab.txt','\t',[17 0 17 n-1])
I get the following output:
M =
-5 0 15 20 40 250 0
This is the output I would like to see, but the problem is that in some cases the length of this vector will change. I tried the following:
M = dlmread('constant_file_matlab.txt','\t',[17 0 17 end])
but is not working. Therefore my questions is: how can I read one specific row in my txt-file from the first to the last value?
However, ideally I would like to do the same as mentioned above, but with text notes at the end of each row (see txt-file: constant_file_matlab2). Is there a method to read this file with notes row by row?
Thank you.
  2 Comments
johan
johan on 16 Jan 2019
Hello Madhan Ravi,
Thanks for your response.
Unfortunately, it is not returning the data in the proper way with this function. If I apply this function I get:
Warning: Variable names were modified to make them valid MATLAB identifiers. The original names are saved in the VariableDescriptions property.
x =
46×1 table
x20
____
12
17
18
17
17
0
0
0
0
0
0
0
0
104
0.74
1
3
2.15
1
400
0
0.01
0.6
9
6
4
0.1
2.6
0.7
6.85
3.9
0.95
2
1.05
1.68
-5
0
15
20
40
250
0
1
0
0
1
The readtable function creates a table by reading column orientated data.

Sign in to comment.

Accepted Answer

Jan
Jan on 16 Jan 2019
Edited: Jan on 16 Jan 2019
"For a project I would like to read a certain row of the txt-file constant_file_matlab.txt"
function S = ReadLineOfFile(FileName, L)
[fid, msg] = fopen(FileName, 'r');
assert(fid ~= -1, msg);
for k = 1:L-1
fgetl(fid); % skip one line
end
S = fgetl(fid); % reply the L.th line:
fclose(fid)
end
Now you want to parse the line:
S = '0.10 2.60 0.70 6.85 3.90 0.95 2.00 1.05 1.68 %notes'
% Actually:
% S = ReadLineOfFile('constant_file_matlab.txt', 17)
[Value, ~, ~, nextindex] = sscanf(S, '%g ', [1, inf]);
Comment = S(nextindex:end)

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!