How to access substrings out of cell array with indexing?

조회 수: 2 (최근 30일)
Osvald Ljungstrand
Osvald Ljungstrand 2016년 12월 20일
댓글: Osvald Ljungstrand 2016년 12월 21일
Hi all, I searched a lot through the community as there was normally someone with a similar problem. But this time I was not able to find a solution.
I have a cell array (over 13,000x1) with strings and need to extract the number within. Example:
message = { 'error(1): occured due to A' ; ...
'error(25): occured due to B' ; ...
'error(306): occured due to C' };
With 'regexp' I can identify the position of the number:
[a,e] = regexp(message,'\(\d*\)');
Normally I prefer logical indexing but couldn't find a nice solution to access the substrings within a cell array. So for this small array I can extract the number with a loop
number = zeros(size(message,1),1);
for i=1:size(message,1)
number(i) = str2double(message{i}(a{i}+1:e{i}-1));
end
But the for-loop is very time consuming for big cell arrays. I would prefer to use the existing a and e array.
Does anyone has a better way to access substrings within cell arrays?

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 12월 20일
message = { 'error(1): occured due to A' ; ...
'error(25): occured due to B' ; ...
'error(306): occured due to C' }
a = regexp(message,'\d+','match','once')
out = str2double(a)

추가 답변 (1개)

David Barry
David Barry 2016년 12월 20일
If you are using R2016b then you can make use of the new String datatype and then use the extractBetween function. This should be very quick.
message = { 'error(1): occured due to A' ; ...
'error(25): occured due to B' ; ...
'error(306): occured due to C' };
message = string(message);
nums = extractBetween(message, '(', ')');
nums = str2double(nums);
  댓글 수: 2
David Barry
David Barry 2016년 12월 20일
Or see Andrei's answer if you are using an older release.
Osvald Ljungstrand
Osvald Ljungstrand 2016년 12월 21일
Nonehteless my "message" looks a bit more complex and I can't just copy paste your suggestion, the combination of the 'match' option for regexp with the extractBetween function will solve my problem perfectly. Thank you a lot for your help

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by