Effacer les filtres
Effacer les filtres

How to access substrings out of cell array with indexing?

1 vue (au cours des 30 derniers jours)
Osvald Ljungstrand
Osvald Ljungstrand le 20 Déc 2016
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?

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 20 Déc 2016
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)

Plus de réponses (1)

David Barry
David Barry le 20 Déc 2016
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 commentaires
David Barry
David Barry le 20 Déc 2016
Or see Andrei's answer if you are using an older release.
Osvald Ljungstrand
Osvald Ljungstrand le 21 Déc 2016
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by