how to obtain the number of lines starting with a given string from an external text file and save the numeric value of variables of those lines

2 views (last 30 days)
Hugo
Hugo on 28 Sep 2020
Commented: Hugo on 29 Sep 2020
Hello,
I have an external text file. A part of the text file (example) is shown below:
/AA
/BB
/CC
DRL=1
DRL=2
DRL=4
/XX
/YY
/ZZ
How can I :
-Obtain the number of lines starting with "DRL" and save it to the variable pnumber. In this case pnumber=3
-save the value of those variables in the vector A, in my example A =[1;2;4]
I thank you in advance for any help,
Best regards,
Hugo

Accepted Answer

Sudheer Bhimireddy
Sudheer Bhimireddy on 28 Sep 2020
Another approach:
data = readtable('test.txt'); % test.txt contains the given text
drl_count = sum(strcmp(data.Var1,'DRL'));
drl_value = data.Var2(strcmp(data.Var1,'DRL'));
>> drl_count =
3
drl_value =
1
2
4
  7 Comments

Sign in to comment.

More Answers (1)

Ameer Hamza
Ameer Hamza on 28 Sep 2020
Edited: Ameer Hamza on 28 Sep 2020
Try this
f = fileread('data.txt');
lines = textscan(f, '%s');
lines = lines{1};
idx = cellfun(@(x) x(1)=='/', lines);
lines(idx) = [];
pnumber = numel(lines);
A = cellfun(@(x) sscanf(x, 'DRL=%d'), lines);
data.txt is attached.
  2 Comments

Sign in to comment.

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!