Using i and j as variables in Matlab

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...

As indices into matrix:

mat( i, j ) = 4;

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


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.

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.

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.

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 overwite 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 eachother.

Therfore 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.

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.

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 againt 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.

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.

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.

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.

Because i and j are by default imaginary units. If you assign i and j other values, the default value will be overwritten. This may cause confusion. However, a good way to avoid it is to use 1i and 1j as imaginary units. In general, you can use ni and nj to represent imaginary numbers.

For example:

>> i

ans =

   0.0000 + 1.0000i

>> i=2

i =


>> 1i

ans =

   0.0000 + 1.0000i

Need Your Help

objective C for-loop break and continue

iphone objective-c for-loop

How can i use a 'break' statement within a for-loop which continues form a specified label?

Finding out the CPU clock frequency (per core, per processor)

c++ cpu cpu-speed

Programs like CPUz are very good at giving in depth information about the system (bus speed, memory timings, etc.)