Why am I getting the complex number in the for loop?
5 views (last 30 days)
Show older comments
Zhuoyi Chen
on 11 Oct 2019
Commented: Zhuoyi Chen
on 11 Oct 2019
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?
0 Comments
Accepted Answer
Fangjun Jiang
on 11 Oct 2019
Edited: Fangjun Jiang
on 11 Oct 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)))
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!