MATLAB: How to change all variable names in a Matlab function

replace variable namessearch and replacevariables

I would like to have a method for duplicating a function and at the same time rename all variables in the file so that they have a specific prefix, for example:
function c = main(m)
a = m*2
b = m*3
c = a+b+m;
should be duplicated and the prefix 'main_' should be added. The new function becomes:
function main_c = main(main_m)
main_a = main_m*2
main_b = main_m*3
main_c = main_a+main_b+main_m;
It can be done in the Matlab editor ( see here ) but I would like to do it via code.
Thanks for any inputs 🙂

Best Answer

You need a powerful parser, which can distinguish names of variables from (shadowed) functions, strings and longer names, which contains the string as a part only.
Most likely somebody has written such a thing already and published it in the FEX. What about < http://www.mathworks.com/matlabcentral/fileexchange/15924-farg--a-pedestrian-m-file-parser-showing-all-used-functions--syntax> It should contain all you need. But the modification of the code to replace the strings is not trivial.
I guess that solving the problem in the editor is much faster than creating a powerful parser as a program. Using an automatic tool is only useful, if the codes are large and complicated. And especially in this case, finding potential bugs of the parsing+replacing procedure is very hard. I expect, that the required time for validating and debugging will exceed the advantage in runtime massively.
The efficiency of a program is determined by the time required to solve the problem, not by the runtime only.