In a comment to my own comment (advising the OP to not use i or j as loop variable names), Guillaume wrote the following:
Stephen, you say that in every single post that uses i or j as an iterator. I don't agree with it because:
a) it stands very little chance of breaking anything. Matlab uses 1i and 1j to represent the imaginary unit. i and j are just functions that return these values.
b) I'd argue that mathworks was wrong to create these functions in the first place. i and j are used as iterating variables in zillions of computer books. Matlab shouldn't hijack such a common variable name. (Matlab needs namespaces badly).
However, I'd say that in complex code, you should use variable names that explain better their purpose.
Both of a) and b) are good points, but actually my main motivation for making these comments to OP's was based more along the idea of "it is likely the OP is not aware of this information, here is something small and easy to learn about MATLAB". I do feel that it is appropriate on Answers to introduce an OP to new information, or a new way of doing something that they may not be aware of, and indeed occasionally an OP has responded with something along the lines of "oh, thank you, I did not know that".
However I recognize that misusing i or j is unlikely to break as much as an assignment to length or mean or sum (or my favorite false=true), although it does happen, as these answers indicate. For better or worse, MATLAB does allow users to assign these names without warning (YES to namespaces, or atleast some syntax to force this kind of shadowing).
Apparently there used to be a page on the MathWorks website entitled "Avoid Using i and j for Variables", but it does not seem to exist any more. Documentation for older MATLAB versions explicitly recommended not using i and j as variable names, for JIT-related speed reasons.
- Is this issue still relevant?
- Is it useful to give an OP new information that they likely are not aware of, even if it does not directly affect the outcome of their question?
- Should i and j be treated differently to shadowing of other inbuilt functions or variables, even if their posted code does not break?
- Is it appropriate to make a comment about their usage?
- Under what circumstances, and for which OP's?
Best Answer