How to read lines from cell

5 次查看(过去 30 天)
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 个)

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