How to read lines from cell

조회 수: 4 (최근 30일)
A-Rod
A-Rod 2024년 7월 5일
댓글: A-Rod 2024년 7월 10일
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
dpb
dpb 2024년 7월 6일
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 2024년 7월 8일
my bad, please find attached the file.
anyother comment please let me know.
thanks

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2024년 7월 8일
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"
  댓글 수: 1
A-Rod
A-Rod 2024년 7월 10일
it works, thanks a lot Stephen23

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matlab Pro
Matlab Pro 2024년 7월 7일
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
A-Rod
A-Rod 2024년 7월 8일
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+.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by