Why am I getting the complex number in the for loop?

5 visualizzazioni (ultimi 30 giorni)
I was trying to compute a matrix of values using the following codes (simplified):
n = 5;
xk = zeros(n+1);
for i = 0:n
Tempprod = 1;
for j = 0:n
xk(i+1,j+1) = cos(pi*(2j+1)/(2*(n+1)));
end
end
The output of the above code is
xk =
1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i
1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i
1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i
1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i
1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i
1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i 1.1014 - 0.1418i
However, if I tried to compute one single value, say , I tried
cos(pi*(2*1+1)/(2*(5+1)))
and Matlab gave me the answer:
ans =
0.7071
So what I went wrong in the codes before? How can I fix it?

Risposta accettata

Fangjun Jiang
Fangjun Jiang il 11 Ott 2019
Modificato: Fangjun Jiang il 11 Ott 2019
Try not to use variable name i and j. Try this
clear all
i
j
or you missed one "*"
cos(pi*(2*j+1)/(2*(n+1)))

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by