How to read lines from cell

5 views (last 30 days)
A-Rod
A-Rod on 5 Jul 2024
Commented: A-Rod on 10 Jul 2024
this time I'm trying to process data from a .txt file.
my goal is to extrat the information at specific lines.
I load my file
temp3 = regexp(fileread('DT_Diagra_ScanTool_DT62234_T0410_SHAP_001.txt'), '\r?\n', 'split')';
I got a 680x1 cell
I made and index to find the line in whic is the value I wnat.
idc = strfind(temp3,'PID 01');
idx = ~cellfun('isempty',idc);
is there any way to get all the '0' and '1' in that row?
after that I will also need to get the next 4 lines below and end up getting below values
0000 0000
0000 0111
1110 0101
1110 0101
as always any feedback will be high appreciated
  2 Comments
dpb
dpb on 6 Jul 2024
As always, attach a sample text file itself...more than likely you can read the file directly avoiding the cells, but without the file to work with, we're shooting in the dark...
A-Rod
A-Rod on 8 Jul 2024
my bad, please find attached the file.
anyother comment please let me know.
thanks

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 8 Jul 2024
S = readlines('T04102.txt');
X = find(startsWith(S,'PID 01'));
F = @(x) regexp(S(x:x+3),'[01]{4}\s+[01]{4}','once','match');
C = arrayfun(F,X, 'uni',0);
C{:}
ans = 4x1 string array
"1000 0001" "0000 0100" "0000 0000" "0000 0000"
ans = 4x1 string array
"0000 0000" "0000 0111" "1110 0101" "1110 0101"

More Answers (1)

Matlab Pro
Matlab Pro on 7 Jul 2024
As @dpb commented - the need to attach the raw data so it will help all of us to debug
Anyhow -I have imitated your data:
Look at the solution below
I assume that temp3 is a cellarray
I have used "contains" function instead of "strfind"
The rest - extract relevant data
% Imitating the READ output of the file
temp3 = repmat({''}, 680,1);
temp3{215} = 'PID 01000 000MIL on; fault code entries';
temp3{216} = '0000 0100';
temp3{217} = '0000 0000';
temp3{218} = '0000 0000Monitor status since DTCs cleared';
% Extracting data
idx = cell2mat(cellfun(@(x) contains(x, 'PID 01'),temp3,'uni',0));
i1 = find(idx);
for iLine = 0:3
re = regexp(temp3{i1+iLine},'\d+\s+\d+','match');
line1 = re{1}; % get all the '0' and '1' in that row
disp(line1);
end
  1 Comment
A-Rod
A-Rod on 8 Jul 2024
thank you for your feedback.
this works and it gives what I'm looking for but when I load my .txt file I got this error:
Error using regexp
Invalid option for regexp: \d+\s+\d+.

Sign in to comment.

Categories

Find more on Get Started with MATLAB 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!