Simplify regexprep to avoid having to use a loop

1 visualización (últimos 30 días)
SpeedyGonzales
SpeedyGonzales el 31 de Mzo. de 2015
Respondida: SpeedyGonzales el 1 de Abr. de 2015
Hi,
I have a list of Identifiers representing a hierarchy that I need to change slightly in order to process them. The Identifiers are use '_' in order to separate hierarchy levels. What I want to do is to replace all '_' from the 3rd '_' onwards.
I was able to find the regexprep code, but I am only able to replace one '_' at the time and then using a loop. The code I was able to come up with looks as follows:
clear;clc;
nodes ={'RB_AA_AL_CTA'; 'RB_AA_AL_HDGE'; 'RB_AA_CA'; 'RB_AA_EH'; 'RB_AA_EQ_DMLC_EUR'; 'RB_AA_EQ_DMLC_USD'; 'RB_AA_EQ_DMLC_JPY';};
for x=1:length(nodes)
for y = 2: length(cell2mat(strfind(nodes(x),'_')))
nodes(x) = regexprep(nodes(x),'_','-',3);
end
end
I am wondering now whether it is possible to simplify this such that I don't have to use a loop? Thanks Sven

Respuesta aceptada

per isakson
per isakson el 1 de Abr. de 2015
Editada: per isakson el 1 de Abr. de 2015
At least different
for jj = 1:length(nodes)
ix_ = find(nodes{jj}=='_');
if length(ix_) >= 3
nodes{jj}(ix_(3):end) = strrep(nodes{jj}(ix_(3):end), '_', '-' );
end
end
however, slower :(
&nbsp
This is better
for jj = 1:length(nodes)
ix_ = find(nodes{jj}=='_');
if length(ix_) >= 3
nodes{jj}(ix_(3:end)) = '-';
end
end

Más respuestas (1)

SpeedyGonzales
SpeedyGonzales el 1 de Abr. de 2015
Thank you! This is helpful...

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by