Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More on using i and j as variables in Matlab: speed

The Matlab documentation says that

For speed and improved robustness, you can replace complex i and j by 1i. For example, instead of using

a = i;

use

a = 1i;

The robustness part is clear, as there might be variables called i or j. However, as for speed, I have made a simple test in Matlab 2010b and I obtain results which seem to contradict the claim:

>>clear all

>> a=0; tic, for n=1:1e8, a=i; end, toc
Elapsed time is 3.056741 seconds.

>> a=0; tic, for n=1:1e8, a=1i; end, toc
Elapsed time is 3.205472 seconds.

Any ideas? Could it be a version-related issue?

After comments by @TryHard and @horchler, I have tried assigning other values to the variable a, with these results:

Increasing order of elapsed time:

"i" < "1i" < "1*i" (trend "A")

"2i" < "2*1i" < "2*i" (trend "B")

"1+1i" < "1+i" < "1+1*i" (trend "A")

"2+2i" < "2+2*1i" < "2+2*i" (trend "B")

like image 902
Luis Mendo Avatar asked Aug 10 '13 15:08

Luis Mendo


People also ask

What is j and I in MATLAB?

In MATLAB®, i and j represent the basic imaginary unit. You can use them to create complex numbers such as 2i+5 . You can also determine the real and imaginary parts of complex numbers and compute other common values such as phase and angle.

Can you use i as a variable in MATLAB?

Shadowing Matlab's built-in functions is without doubt a bad programming practice. Therefore TMW suggests not to use i and j as names of variables, see: techdoc: Avoid Using i and j for Variables. Today MLint suggests to use 1i instead of i to get the imaginary value.

Does MATLAB use IM or imaginary numbers j?

You can use j to enter complex numbers. You also can use the character i as the imaginary unit.


1 Answers

I think you are looking at a pathological example. Try something more complex (results shown for R2012b on OSX):

(repeated addition)

>> clear all
>> a=0; tic, for n=1:1e8, a = a + i; end, toc
Elapsed time is 2.217482 seconds. % <-- slower
>> clear all
>> a=0; tic, for n=1:1e8, a = a + 1i; end, toc
Elapsed time is 1.962985 seconds. % <-- faster

(repeated multiplication)

>> clear all
>> a=0; tic, for n=1:1e8, a = a * i; end, toc
Elapsed time is 2.239134 seconds. % <-- slower
>> clear all
>> a=0; tic, for n=1:1e8, a = a * 1i; end, toc
Elapsed time is 1.998718 seconds. % <-- faster
like image 180
SheetJS Avatar answered Oct 23 '22 08:10

SheetJS