MATLAB Answers

Make a string an acceptable matlab file name

조회 수: 83(최근 30일)
Lucas
Lucas 10 Sep 2012
편집: William Smith 26 Mar 2018
I'm working on a process to automate out model conversion into reference models and I was wondering if there was a way to take a string and make it into a valid MatLab name.
Like you can’t have numbers as the first character in a name, so if I have a model that has a subsystem named ‘2a_Subsystem’, and I right-click and hit ‘convert to model block’ it gives me a new model with the name of ‘a_Subsystem’. If I have another subsystem called ‘3a_Subsystem’ and I convert it to a model block it gives me a new model with that name ‘a_Subsystem0’.
Is there a function that I can pass a string and convert it to a valid MatLab name like it does when I click on convert to model block? Maybe one that can check to see if that name is currently being used in that directory and adds a number to it like it does above. I can do the second part if there isn’t a function that’ll check for something like that already. Thanks!

  댓글 수: 0

댓글을 달려면 로그인하십시오.

채택된 답변

Sean de Wolski
Sean de Wolski 10 Sep 2012

  댓글 수: 0

댓글을 달려면 로그인하십시오.

추가 답변(1개)

William Smith
William Smith 26 Mar 2018
편집: William Smith 26 Mar 2018
I found urlencode() and urldecode() work nicely, and I particularly like the reversibility, so you can parse the filename to recover the original string.
One caveat : in Windows, * is a reserved character, but Matlab urlencode does not encode that. Although it does decode it. The appears to be the only Windows reserved character that urlencode does not encode. Different languages appear to disagree about whether * should be urlencoded, see https://stackoverflow.com/questions/6533561/urlencode-the-asterisk-star-character/6533607#6533607
So I wrote my own two short functions:
function urlOut = urldecode(urlIn)
urlOut = char(java.net.URLDecoder.decode(urlIn,'UTF-8'));
end
function urlOut = urlencode(urlIn)
urlIn = replace(urlIn, '*', '%2A');
urlOut = char(java.net.URLEncoder.encode(urlIn,'UTF-8'));
end

  댓글 수: 0

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by