Is MATLAB is automatically concatenating data from a text file?
조회 수: 1 (최근 30일)
이전 댓글 표시
I have an input line of text that looks like this:
Band ID: 0 AD ID: 43 Scan ID: 0 LRT/HRT: 0 Valid Flag: 0
I’ m using the following regexp command to split the string;
Data = regexp(LineText,’ +’,’split’);
Actual output:
Band ID: 0AD ID: 43Scan ID: 0LRT/HRT: 0Valid Flag: 0
Expected output:
Band ID: 0 AD ID: 43 Scan ID: 0 LRT/HRT: 0 Valid Flag: 0
Where all numerical values are in there own cell. Also note that if the tabs that occur after each number are only spacs, I get the required result.
I don’t believe I’ve seen the regexp function behave in this manner. Is this a case where regexp is choking on the tabs in the text file? Or is my regexp too generic?
댓글 수: 0
채택된 답변
Cedric
2013년 5월 13일
편집: Cedric
2013년 5월 13일
What are you trying to achieve, extract the numbers? The space in the pattern ' +' won't match tabs actually, but '\s+' would (match spaces, tabs, any "white space"). If your goal were to extract numbers, you could go for
>> match = regexp(LineText,'\d+','match') ;
>> num = str2double(match)
num =
0 43 0 0 0
If you had a whole file with this structure, you could process it in one shot instead of line by line (for the example, I repeated several times this LineText that you provided and just incremented the AD value)..
>> buffer = fileread('brad.txt') ;
>> num = str2double(regexp(buffer,'\d+','match')) ;
>> num = reshape(num, 5, []).'
num =
0 43 0 0 0
0 44 0 0 0
0 45 0 0 0
0 46 0 0 0
and you could use more elaborate patterns if numbers were not integers, e.g. '[\d\.-]+' for matching positive and negative floating points as well.
댓글 수: 2
Cedric
2013년 5월 14일
You're welcome Brad. I think that we all have still have always something to learn about these regexp to be honest ;-) I could not recommend enough the official doc actually if you want to learn; it is one of the best documents that I have seen about them, in the sens that it is quite concise, yet very explicit with examples and it covers a lot of material quite well. You can find it there:
Take the document called Programming Fundamentals in the MATLAB section, on pages 2-26 to 2-85.
추가 답변 (1개)
David Sanchez
2013년 5월 13일
Is this what you want?
s='Band ID: 0 AD ID: 43 Scan ID: 0 LRT/HRT: 0 Valid Flag: 0';
data= regexp(s,'\t','split')
you will end up with an cell containing the data string.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!