Simplify regexprep to avoid having to use a loop

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

Risposta accettata

per isakson
per isakson il 1 Apr 2015
Modificato: per isakson il 1 Apr 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

Più risposte (1)

SpeedyGonzales
SpeedyGonzales il 1 Apr 2015
Thank you! This is helpful...

Categorie

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

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by