Looping Error: subscript indices must either be real positive integers or logicals
조회 수: 1 (최근 30일)
이전 댓글 표시
x=(7*pi)/4
k=12
for n = 1:k
cossum(x) = ((-1^(n))*(x.^(2*n)))/(factorial(2*n));
end
When x is a fraction I get the subscript indices error. When its a whole number I do not. How to I run this loop with x as a decimal?
댓글 수: 0
답변 (1개)
Guillaume
2016년 2월 11일
For a start x does not vary in the loop, so you'd be storing the result of the loop always in the same element of cossum. Secondly, you must use integer indices as the error message says. There's no reason to use x as an index in any case. I assume that's what you wanted:
x=(7*pi)/4
k=12
for n = 1:k
cossum(n) = ((-1^(n))*(x.^(2*n)))/(factorial(2*n));
end
Note that you don't need a loop in the first place. You can use vectorised operations:
x=(7*pi)/4;
k=12;
n = 1:k;
cossum = ((-1.^n)*(x.^(2*n))) ./ factorial(2*n)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!