Looping Error: subscript indices must either be real positive integers or logicals

조회 수: 1 (최근 30일)
Josh
Josh 2016년 2월 11일
답변: Guillaume 2016년 2월 11일
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?

답변 (1개)

Guillaume
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)

카테고리

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