필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
Neha W
Neha W 2016년 9월 24일
편집: dpb 2016년 9월 26일
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