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

조회 수: 4 (최근 30일)
Zhuoyi Chen
Zhuoyi Chen 2019년 10월 11일
댓글: Zhuoyi Chen 2019년 10월 11일
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?

채택된 답변

Fangjun Jiang
Fangjun Jiang 2019년 10월 11일
편집: Fangjun Jiang 2019년 10월 11일
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)))

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by