How do I get the sum for every i = 1: N-1?

4 次查看(过去 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.

采纳的回答

Image Analyst
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

更多回答(1 个)

dpb
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 个评论
Neha W
Neha W 2016-9-24
The reason for excluding constant is that I am working on special case called as permutation polynomials. But you are right Sir, I will include only single variable.
dpb
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 CenterFile Exchange 中查找有关 Polynomials 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by