How to access substrings out of cell array with indexing?

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