Looping Error: subscript indices must either be real positive integers or logicals
1 view (last 30 days)
Show older comments
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 Comments
Answers (1)
Guillaume
on 11 Feb 2016
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 Comments
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!