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!