Simplify regexprep to avoid having to use a loop

1 vue (au cours des 30 derniers jours)
SpeedyGonzales
SpeedyGonzales le 31 Mar 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

Réponse acceptée

per isakson
per isakson le 1 Avr 2015
Modifié(e) : per isakson le 1 Avr 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

Plus de réponses (1)

SpeedyGonzales
SpeedyGonzales le 1 Avr 2015
Thank you! This is helpful...

Catégories

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

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by