145

i and j are very popular variable names (see e.g., this question and this one).

For example, in loops:

for i=1:10,
    % Do something...
end

As indices into a matrix:

mat(i, j) = 4;

Why shouldn't they be used as variable names in MATLAB?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 8
    Of course I won't flag it as such, but judging from the answers I'd say this is "primarily opinion-based". ;-) I personally wouldn't give up on `i`, `j`, `k` as the generic loop variable names. – A. Donda Apr 27 '15 at 13:48
  • 2
    @A.Donda well, this is **your** opinion ;) – Shai Apr 27 '15 at 13:55

9 Answers9

178

Because i and j are both functions denoting the imaginary unit:

So a variable called i or j will override them, potentially silently breaking code that does complex maths.

Possible solutions include using ii and jj as loop variables instead, or using 1i whenever i is required to represent the imaginary unit.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 42
    It is also worthy to note that even if you're not breaking anything, execution time is still sacrificed to resolve the `i` and `j` variable names. – Eitan T Mar 05 '13 at 14:48
  • 16
    @Eitan: Can you actually back that up in any concrete conclusive way in a JIT compiled version of Matlab? I have never found it to be the case (and simple tests calling a `for` loop 1 billion times show no statistical difference in timing). For all we know there is special code to handle exactly this and using variables other than `i` and `j` (and `k`?) is actually slightly slower. And differences that do exist are miniscule to non-existent in real life. There simply is no reason NOT to use `i` and `j` as regular variables -they just have to be used properly like any other Matlab function. – horchler Jun 10 '13 at 21:08
  • 5
    @horchler Well, the official docs state [here](http://goo.gl/risIl) that overriding standard MATLAB data classes "can negatively affect performance", and [here](http://goo.gl/bzQ9a) it is implied to avoid overriding complex constants for reasons of speed, as well as robustness. In [older docs of R2009b](http://goo.gl/PVwFk) it is explicitly recommended against overriding complex constants, as this may hinder JIT acceleration. Variable name resolution is perhaps miniscule, but it may be significant if repeated millions of times. – Eitan T Jun 11 '13 at 14:18
  • 16
    In ancient versions of Matlab maybe. I used to see that myself. But not any more with R2012a+ (OS X) at least. And I saw no difference when calling a `for` loop 1 billion times and trying all manner of timing schemes. I'm seeing new SO users being told that perfectly valid code is wrong because they're using `i` and `j` to iterate loops. Frankly it's just silly and people are missing the more important point of this question: that `i` and `j` shouldn't even be used for the imaginary unit if one wants to write readable modern Matlab code. – horchler Jun 11 '13 at 15:16
  • 3
    @horchler I agree for the most part, but the R2013 docs also confirm that MATLAB doesn't always accelerate variable name resolution properly. In any case, releases as early as R2009 are still widespread, so I'd recommend taking that into consideration when writing code. And maybe the correct wording should've been "...execution time _may_ still be sacrificed..." – Eitan T Jun 11 '13 at 16:56
  • 12
    my major time saving is when doing a search for ii. Searching for i can be a real pain – craq Feb 18 '14 at 14:07
  • Yes. use ii, jj instead of i, j. That's what I always do. – wsdzbm Sep 15 '15 at 17:17
  • 1
    `ii` have a striking resemblance with `1i` so that would be nearly as bad a using `i` in my opinion. If possible (eg. names are not too verbose), always prefer names relating the purpose of the variable. If the variable is the index of a vector, it can be named `idx` for example. In case the variable is used locally, for a short piece of code, it can be named to just about anything, `k`, `kk`, `foo`, ... Only note here that loops does not have a separate scope in Matlab, so the variable can remain in memory for a long time in case the function/script is long. – patrik Jan 18 '16 at 08:22
  • 1
    Official MATLAB style guidelines suggest using the prefix 'i' when iterating, e.g. looping over `iPassenger = 1:nPassenger` – jebob Feb 29 '16 at 20:08
66

It is good practice to avoid i and j variables to prevent confusion about them being variables or the imaginary unit.

Personally, however, I use i and j as variables quite often as the index of short loops. To avoid problems in my own code, I follow another good practice regarding i and j: don't use them to denote imaginary numbers. In fact, MATLAB's own documentation states:

For speed and improved robustness, you can replace complex i and j by 1i.

So rather than avoiding two very commonly used variable names because of a potential conflict, I'm explicit about imaginary numbers. It also makes my code more clear. Anytime I see 1i, I know that it represents sqrt(-1) because it could not possibly be a variable.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shoelzer
  • 10,648
  • 2
  • 28
  • 49
  • 3
    It is indeed good practice to use `1i`. However, changing the meaning of `i` and `j` may lead to hard-to-debug errors such as [this one](http://www.stackoverflow.com/questions/13860222/what-is-complex-scalar-type-invalid-as-index-value). – Shai Feb 14 '13 at 07:49
  • 1
    @Shai Good point. I tweaked my answer to acknowledge that avoiding `i` and `j` is best, but explained how my personal coding style does not follow that rule. – shoelzer Feb 14 '13 at 15:10
  • 2
    Note that the speed mentioned does not seem to be very significant: http://stackoverflow.com/questions/18163454/more-on-using-i-and-j-as-variables-in-matlab-speed – Dennis Jaheruddin Aug 14 '13 at 09:10
  • 1
    Totally agree! The good practice is to ALWAYS use `1i` and not `i` for complex math. Let's think of imaginary number as `1i` and take `i` as imaginary number a bad practice. Not the other way around. Using `i`, `ii`, `iii` is common practice in Matlab and there is no problem when people stick to `1i` and `1j` for complex number. Also Matlab respects this and this one doesn't decrease performance (as far as I tested) as stated in previous answer. – SddS Jul 03 '17 at 10:12
  • i and j shouldn't be used anyway - those numbers mean **something** - use a name that describes the purpose (row_n, elementNo, listItemIndex, etc.). **So** much easier for someone to understand what you are doing, to debug, etc. The extra time spent is more than worth the gain in long-term maintainability for anything more than a throw-away script - even with the Matlab Editor being well behind most other modern IDEs. – LightCC Aug 13 '19 at 01:36
32

In old versions of MATLAB, there used to be a good reason to avoid the use of i and j as variable names - early versions of the MATLAB JIT were not clever enough to tell whether you were using them as variables or as imaginary units, and would therefore turn off many otherwise possible optimizations.

Your code would therefore get slower just by the very presence of i and j as variables, and would speed up if you changed them to something else. That's why, if you read through much MathWorks code, you'll see ii and jj used fairly widely as loop indices. For a while, MathWorks might even have unofficially advised people to do that themselves (although they always officially advise people to program for elegance/maintainability rather than to whatever the current JIT does, as it's a moving target each version).

But that's rather a long time ago, and nowadays it's a bit of a "zombie" issue that is really much less important than many people still think, but refuses to die.

In any recent version, it's really a personal preference whether to use i and j as variable names or not. If you do a lot of work with complex numbers, you may want to avoid i and j as variables, to avoid any small potential risk of confusion (although you may also/instead want to only use 1i or 1j for even less confusion, and a little better performance).

On the other hand, in my typical work I never deal with complex numbers, and I find my code more readable if I feel free to use i and j as loop indices.


I see a lot of answers here that say It is not recommended... without saying who's doing that recommending. Here's the extent of MathWorks' actual recommendations, from the current release documentation for i:

Since i is a function, it can be overridden and used as a variable. However, it is best to avoid using i and j for variable names if you intend to use them in complex arithmetic. [...] For speed and improved robustness, you can replace complex i and j by 1i.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
16

As described in other answers, the use of i in general code is not recommended for two reasons:

  • If you want to use the imaginary number, it can be confused with or overwritten by an index
  • If you use it as an index it can overwrite or be confused with the imaginary number

As suggested: 1i and ii are recommended. However, though these are both fine deviations from i, it is not very nice to use both of these alternatives together.

Here is an example why (personally) I don't like it:

val2 = val + i  % 1
val2 = val + ii % 2
val2 = val + 1i % 3

One will not easily be misread for two or three, but two and three resemble each other.

Therefore my personal recommendation would be: In case you sometimes work with complex code, always use 1i combined with a different loop variable.

Examples of single letter indices that for if you don't use many loop variables and letters suffice: t,u,k and p

Example of longer indices: i_loop,step,walk, and t_now

Of course this is a matter of personal taste as well, but it should not be hard to find indices to use that have a clear meaning without growing too long.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
  • 1
    1i denotes the imaginary unit (also Matlab variables names can't begin with a number) – lib Feb 20 '13 at 16:28
  • 2
    @DennisJaheruddin: shameless plug: Use my MATLAB syntax highlighting [userscript](https://github.com/amroamroamro/prettify-matlab/raw/master/js/prettify-matlab.user.js) for Stack Overflow. In the last example, `1i` will be differently colored as a number :) – Amro Apr 22 '13 at 08:55
  • 2
    Straight from `doc i` and `doc j`: "For speed and improved robustness, you can replace complex i and j by 1i." IMO, in current Matlab there is no reason to not use `i` and `j` in loops, etc., or to use anything other than `1i` to denote the imaginary unit (`1j` works too). The only exception is when passing strings to the always-slightly-incompatible Symbolic engine. Strange that `help 1i` and `doc 1i` don't work though. – horchler Jun 02 '13 at 23:45
12

It was pointed out that 1i is an acceptable and unambiguous way to write sqrt(-1), and that as such there is no need to avoid using i. Then again, as Dennis pointed out, it can be hard to see the difference between 1i and ii. My suggestion: use 1j as the imaginary constant where possible. It's the same trick that electrical engineers employ - they use j for sqrt(-1) because i is already taken for current.

Personally I never use i and j; I use ii and jj as shorthand indexing variables, (and kk, ll, mm, ...) and 1j when I need to use complex numbers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Floris
  • 45,857
  • 6
  • 70
  • 122
  • 2
    "it can be hard to see the difference between `1i` and `ii`" And even more the difference between `1` and `l` and between `O` and `0`. That's why the first step I do in an fresh MATALB installation is changing the default font size. – glglgl Feb 20 '14 at 09:05
6

Confusion with the imaginary unit has been well covered here, but there are some other more prosaic reasons why these and other single-letter variable names are sometimes discouraged.

  1. MATLAB specifically: if you're using coder to generate C++ source from your MATLAB code (don't, it's horrible) then you are explicitly warned not to reuse variables because of potential typing clashes.

  2. Generally, and depending on your IDE, a single-letter variable name can cause havoc with highlighters and search/replace. MATLAB doesn't suffer from this and I believe Visual Studio hasn't had a problem for some time, but the C/C++ coding standards like MISRA, etc. tend to advise against them.

For my part I avoid all single-letter variables, despite the obvious advantages for directly implementing mathematical sources. It takes a little extra effort the first few hundred times you do it, but after that you stop noticing, and the advantages when you or some other poor soul come to read your code are legion.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
xenoclast
  • 1,635
  • 15
  • 26
4

By default i and j stand for the imaginary unit. So from MATLAB's point of view, using i as a variable is somehow like using 1 as a variable.

yo'
  • 811
  • 11
  • 22
  • 5
    i don't think it's quite like that. i is a legit variable name, so you can actually use i and j as variable names. it will, as a previous answer mentions, mask the imaginary meaning. 1 is not a legit variable name. it's totally fine if you never use complex numbers. – thang Feb 09 '13 at 21:08
  • @thang that's why I said "somehow like" and not "like". I know there's a difference. OP asked why they shouldn't be used, I tried to explain that it's because they already express a number. – yo' Feb 09 '13 at 21:12
  • 2
    ok, sorry, i don't know what *somehow like* means. for me it's clearly different because well, you can't use 1 as a variable even if you wanted to... but i see where you're coming from. – thang Feb 09 '13 at 21:15
  • you _can_ use them, as you can also use existing function names for variables (and at the same time corrupting those builtin functions/constants for further use). Whether you really want that is another thing (imo simple answer: no) – Gunther Struyf Feb 09 '13 at 22:12
  • 1
    Sorry, but this explanation makes no sense. The `i` and `j` are actually functions returning the value of the imaginary unit. It is possible to use a variable with the same name as a function in a scope. This will however shadow the function. – patrik Nov 30 '15 at 15:36
4

Any non-trivial code contains multiple for loops, and the best practices recommend you use a descriptive name indicative of its purpose and scope. For times immemorial (and unless its 5-10 lines script that I am not going to save), I have always been using variable names like idxTask, idxAnotherTask and idxSubTask etc.

Or at the very least doubling the first letter of the array it is indexing e.g. ss to index subjectList, tt to index taskList, but not ii or jj which doesn't help me effortlessly identify which array they are indexing out of my multiple for loops.

  • It is best to avoid explicit loops in MATLAB (as it is extremely slow). Many things can be expressed as matrix and vector operations. – Peter Mortensen Mar 23 '21 at 21:23
3

Unless you are a very confused user I think there is very little risk in using variable names i and j and I use them regularly. I haven't seen any official indication that this practice should be avoided.

While it's true that shadowing the imaginary unit could cause some confusion in some context as mentioned in other posts, overall I simply don't see it as a major issue. There are far more confusing things you can do in MATLAB, take for instance defining false=true

In my opinion the only time you should probably avoid them is if your code specifically deals with imaginary numbers.

gregswiss
  • 1,456
  • 9
  • 20
  • Can you please comment when down-voting. For example with a Mathworks link indicating that the practice is not recommended (which has been stated by multiple posters without referencing any official guideline). In fact using 'i' in loops is being used in official examples by the Mathworks. In my experience it makes the code clear and concise and is very common practice. – gregswiss Oct 13 '15 at 06:13
  • 1
    Citing the [documentation](http://mathworks.com/help/matlab/ref/i.html?s_tid=srchtitle) "Since `i` is a function, it can be overridden and used as a variable. However, it is best to avoid using `i` and `j` for variable names if you intend to use them in complex arithmetic." That, in conjunction with the comment by Eitan T on Oliver's answer ( I guess he timed it) seems sufficient proof. – Adriaan Oct 13 '15 at 10:27
  • 1
    Also note that there's already [an answer from 2013](http://stackoverflow.com/a/17723167/5067311) with the comment mentioned by @Adriaan. – Andras Deak -- Слава Україні Oct 13 '15 at 10:28
  • 1
    so the documentation states IF you intend to use in complex arithmetic, otherwise that doesn't apply - don't know why everyone is so fussy about it here! I was just offering an alternate point of view. – gregswiss Oct 13 '15 at 10:54