How do I get the sum for every i = 1: N-1?
8 ビュー (過去 30 日間)
古いコメントを表示
For N = 600 and degree = 5
After applying certain conditions, I have a polynomial which is of the form:
A = [first middle last]; % excluding constant
first = [171]; middle = [105 370 345]; last = [120];
I need to calculate the sum of the coefficients for every i = 1: N-1 and save it in an array.
0 件のコメント
採用された回答
Image Analyst
2016 年 9 月 24 日
編集済み: Image Analyst
2016 年 9 月 24 日
Try this:
N = 600
degree = 5
for k = 1 : N-1 % Only go up to N-1, as per poster's request.
x = ..... whatever
y = ..... whatever
coeffs = polyfit(x, y, degree);
% Sum the coefficients, not including the constant term, which is the last element.
coeffSum(k) = sum(coeffs(1:end-1));
end
0 件のコメント
その他の回答 (1 件)
dpb
2016 年 9 月 24 日
編集済み: dpb
2016 年 9 月 24 日
To begin with, don't use multiple variables to hold a single variable; use an array instead. Then simply reference the desired subsets of that array.
In your case, an array of Nx6 would hold all the coefficients and if you were to retain the constants simply for consistency and arrange the coefficients in descending order so that coef(n,1) is the coefficient for the n th polynomial fith-order term then the resulting array would be in a form consistent for the builtin functions polyfit|polyval and friends in Matlab. This will likely be beneficial on down the road in your application but even if not for the specific case, the general concept of using the builtins where possible is a powerful multiplier in productivity.
Anyways, once the terms are in such suitable storage, then the desired sum would simply be
sumCoef=sum(coef(1:end-1,1:end-1); % sum coefficients for 1:N-1 excluding constant term (*)
See what conciseness you get by using the array--no summing loops/indices, no trouble generating the output array, etc., etc., etc., ... all handled essentially automagically simply by using Matlab array syntax.
(*) I don't see any reason one wouldn't want to include the last one, too, but that's what the request was for...
2 件のコメント
dpb
2016 年 9 月 24 日
編集済み: dpb
2016 年 9 月 26 日
I was commenting on the N-1 exclusion, not the constants...
ADDENDUM But even given the reason for not including constants, I'd still store the polynomials as above, even if the constant column is all zero. In that case you don't even have to use the 1:end-1 expression to compute the correct sums and still have the benefit of being able to use the builtin polynomial functions where they might be of use.
参考
カテゴリ
Help Center および File Exchange で Polynomials についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!