How to access substrings out of cell array with indexing?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Osvald Ljungstrand
el 20 de Dic. de 2016
Comentada: Osvald Ljungstrand
el 21 de Dic. de 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?
0 comentarios
Respuesta aceptada
Andrei Bobrov
el 20 de Dic. de 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)
0 comentarios
Más respuestas (1)
David Barry
el 20 de Dic. de 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 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!