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?

回答(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