Azzera filtri
Azzera filtri

How to access substrings out of cell array with indexing?

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 20 Dic 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)

Più risposte (1)

David Barry
David Barry il 20 Dic 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 Commenti
David Barry
David Barry il 20 Dic 2016
Or see Andrei's answer if you are using an older release.
Osvald Ljungstrand
Osvald Ljungstrand il 21 Dic 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

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by