Reputation:
I need a bit of help to rename my tabels for xlswrite. I try to use the below code which work as long as the title names are different. However, when I have to identical titels like 'table1' in the example it won't work. How can I search the title strings and if two are identical give them an additional number so my Title array becomes Title={'table1 (1)'; 'table2'; 'table3'; 'table4'; 'table1 (2)';}.
Here is my code
Title={'table1'; 'table2'; 'table3'; 'table4'; 'table1';}
[FileNameBodeWrite,PathNameBodeWrite] = uiputfile({'*.xls'},'Save As', [ '.xls']);
filename=[PathNameBodeWrite FileNameBodeWrite];
t=1/numel(Table);
for ii = 1:numel(Table)
sheet=ii;
xlswrite(filename,Table{ii},sheet,'A1');
e = actxserver('Excel.Application'); % # open Activex server
ewb = e.Workbooks.Open(filename); % # open file (enter full path!)
ewb.Worksheets.Item(ii).Name = Title{ii,1} % # rename sheets
ewb.Save % # save to the same file
ewb.Close(false)
e.Quit
end
Upvotes: 1
Views: 428
Reputation: 125854
The easiest way would be to use matlab.lang.makeUniqueStrings
(or genvarname
prior to R2014a):
Title = {'table1'; 'table2'; 'table3'; 'table4'; 'table1'};
Title = matlab.lang.makeUniqueStrings(Title)
Title =
5×1 cell array
'table1'
'table2'
'table3'
'table4'
'table1_1'
Upvotes: 1
Reputation: 12214
A simple approach looks at the array of title strings and renames those that are repeated.
For example:
Title = {'table1'; 'table2'; 'table3'; 'table4'; 'table1'};
[unique_titles, ia, ic] = unique(Title, 'stable'); % Stable to retain order
counts = accumarray(ic, 1); % Count occurrence of each title
% Iterate only over titles that occur more than once
for ii = ia(counts > 1)
titleidx = find(ic == ii); % Find where titles occur
for jj = 1:counts(ii)
Title{titleidx(jj)} = sprintf('%s (%u)', unique_titles{ii}, jj);
end
end
Which returns:
Title =
5×1 cell array
'table1 (1)'
'table2'
'table3'
'table4'
'table1 (2)'
Upvotes: 0