How to protect arbitrary variable names
5 views (last 30 days)
I am programming functions for large Matlab projects. Inside these functions, I sometimes use arbitrary variable names like 'response', 'val' and - of course - the infamous 'i'.
Since these functions often end up nested inside other functions and scripts, I am worried that me modifying 'i' may interfere with an outside loop, which wouldn't be that cool.
So, before I start giving IDs to every variable, is there a way to make variables unique? Is it even a problem to reassign a variable from the variable space inside a function?
dpb on 4 May 2021
Functions have their own workspace although internal and anonymous functions share their context with the containing workspace...read all about scope starting at <Scope-variables> and related links. And, of course read the doc for function itself and the background information provided there.
Basically, it is not a problem--the variable i inside a local function knows nothing about the base workspace variable i and vice versa.
More Answers (2)
Matt J on 4 May 2021
Edited: Matt J on 4 May 2021
Since these functions often end up nested inside other functions
I can't tell here if you genuinely mean the functions are "nested" in the sense of
or if you just mean that you have functions calling other functions.
It's never a problem to reassign a variable name inside a function which doesn't share its workspace with other functions. If it does share a workspace, as true nested functions do, then yes that can be a problem. It would be peculiar if you were doing that very often, though. The main point of having a function is normally so that you can do computations in the protected isolation of a separate workspace.
Jan on 4 May 2021
I you work on a larger project (any code with > 20 lines), avoid scripts. They are a shot in your knee. With using functions, the problem of re-defined variables in external code vanishes automatically.
Keep the functions small to avoid confusing variables inside it. There are some rule of thumb to limit the size:
- 1000 lines is the maximum
- If you cannot explain, what the function does, in 1 sentence, it is too long.
There are no automatic ways to make variables unique. The programmer has to keep the overview.
The sadowing of built-in function is a more serious problem, because you cannot know, which toolboxes users of your code have installed. Then the rule is to append user-defined folders at the bottom of the path. Then at least Matlab's functions are preferred. For collisions with user defined functions see: https://www.mathworks.com/matlabcentral/fileexchange/27861-uniquefuncnames
In case of conflicts, using packages should help.