Problem with renaming dublicated variablenames
Mostrar comentarios más antiguos
Hi experts,
I want to rename a bunch of variables (ppn) by extending them with '_01' and I want to extend duplicate variablenames with '_02'. The problem is that I get variables named 'BG1028_02_01'. I hope someone can help me!
ppn = {'BG1026';'BG1027';'BG1028';'BG1028';'BG1029';'BG1030'}
for i = 1:length(ppn)-1
j = i + 1;
d = strcmp(ppn{i},ppn{j});
if d == 0;
ppn{i} = strcat(ppn{i},['_01']);
else d = 1;
ppn{i} = strcat(ppn{i},['_01']);
ppn{j} = strcat(ppn{j},['_02']);
continue;
end
end
This is what I get:
ppn =
'BG1026_01'
'BG1027_01'
'BG1028_01'
'BG1028_02_01'
'BG1029_01'
'BG1030'
1 comentario
Kirby Fears
el 16 de Sept. de 2015
Editada: Kirby Fears
el 16 de Sept. de 2015
Do you want a general solution in case you have more than 2 duplicates? In the future, could you end up having 99 duplicates in a row?
Respuesta aceptada
Más respuestas (1)
dpb
el 16 de Sept. de 2015
ppn=strcat(ppn,'_01'); % add the '_01' at the git-go...
[~,~,ib]=unique(ppn); % get a list of unique name positions
[n,ix]=histc(ib,1:5); % count and locate if any duplicates
for i=1:length(n) % and process the list and fixup if needed...
if n(i)>1
for j=2:n(i)
k=ix(i)+j-1;
ppn(k)=strrep(ppn(k),'_01',num2str(j,'_%02d'));
end
end
end
BUT, DO NOT DO THIS!!! See the FAQ for why not and ways to avoid same...
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!