matlab.lang.makeUniqueStrings
Makes strings unique by appending numbers to the ones that collide.
Category: Programming > Functions
Syntax
u = matlab.lang.makeUniqueStrings(str, exclusions)
Changes str so that it does not match any text in exclusions.
u = matlab.lang.makeUniqueStrings(strs)
Makes the elements of a cell array differ from each other.
Description
A string that already differs from everything in exclusions is returned unchanged. Otherwise the function appends _1, _2, and so on until the name is free. For a cell array without exclusions, the first occurrence is kept and later duplicates receive suffixes in order.
A typical use is naming new items, files or table variables without overwriting existing ones.
Input arguments
str- Text or cell array of text to fix.
exclusions- Text or cell array of text that the result must avoid.
Output arguments
u- The unique text, with the same shape as
str.
Example
Avoiding existing names
matlab.lang.makeUniqueStrings('file', {'file', 'file_1', 'other'})
matlab.lang.makeUniqueStrings({'a', 'a', 'b', 'a'})
Output
ans = 'file_2'
ans = 1×4 cell
{'a'} {'a_1'} {'b'} {'a_2'}