Alexandre Willame
Alexandre Willame

Reputation: 455

Imaginary number in loops with 'i' as variable in MATLAB

I have code with a loop in MATLAB, with i is the variable in the iteration:

for i = 1:n
    mycomplexexponential = exp(2*i);
    ....
end

The variable i overrides the imaginary number i inside of the loop. I want the i for mycomplexexponential to refer to the imaginary number.

The problem could be avoided by simply renaming the variable

for ii = 1:n
    mycomplexexponential = exp(2*i);
    ....
end

But for generic reasons, I need to keep the name of the variable as 'i'. How can I do this?

Upvotes: 1

Views: 693

Answers (2)

Royi
Royi

Reputation: 4953

MATLAB convention states you do not use the multiplication operator with imaginary number symbol.
Namely, you should write:

mycomplexexponential = exp(2i);

This should solve the issue.

Upvotes: 1

The Dude
The Dude

Reputation: 1046

Lower case j can also be used for the imaginary unit in MATLAB. So your code would be

for i = 1:n
    mycomplexexponential = exp(2*j);
    ....
end

Upvotes: 1

Related Questions