Evaluate a Polynomial without polyval

I need to create a user defined function that evaluates a vector of the coeficients of a polynomial and a given x value without using the polyval function.
This is what I have so far:
function accum =mypolyval(p,x)
accum = 0;
orderofp = length(p)-1;
n=1:length(p);
for i=1:length(p)
for q=orderofp:-1:0
xtothepower= x^q;
end
y(i) = accum+p(i)*xtothepower;
accum = y(i);
end
end

댓글 수: 1

Guillaume
Guillaume 2018년 2월 23일
Note that even without polyval you can evaluate a polynomial in just one line, without the need for a loop (the only functions needed are sum, numel, .^, .* and :)
However, I assume that you have to use a loop for your assignment.

댓글을 달려면 로그인하십시오.

답변 (3개)

Walter Roberson
Walter Roberson 2017년 5월 5일

0 개 추천

In your line
for q=orderofp:-1:0
xtothepower= x^q;
end
you are overwriting all of xtothepower each iteration.
Dillen.A
Dillen.A 2018년 2월 23일
편집: Dillen.A 2018년 2월 23일

0 개 추천

For anyone still interested in this, my quick solution:
pv=@(p,x) sum(permute(p,[1,3,2]).*(x.^permute(0:length(p)-1,[1,3,2])),3)
y=pv(p,x)
Should work for any 2D matrix, I used permute rather than reshape assuming it is faster. for 3D data you can use [1,2,4,3] in your permute, and then sum over the 4th dim, and so on. polyval is still faster.

댓글 수: 3

Guillaume
Guillaume 2018년 2월 23일
you made a small mistake in that you're evaluating the polynomial the wrong way round, p(end) is the polynomial constant, not p(1), therefore the exponents should be numel(p)-1:-1:0, not 0:numel(p)-1.
Note that permute is never faster reshape. reshape only affects the header of a matrix (the part that says this matrix has n dimensions of size x, y, z...) without ever touching the actual elements of the matrix whereas permute needs to move all these elements around since their order change. In the case of a vector, the two probably take the same time.
A truly generic version (works with any n-dimension x array), using the same algorithm:
pv = @(p, x) sum(shiftdim(p(:), -ndims(x)) .* x .^ shiftdim((numel(p)-1:-1:0).', -ndims(x)), ndims(x)+1)
Dillen.A
Dillen.A 2018년 2월 27일
Thanks for the knowledge. I simply forgot that p was "the wrong way around" as I always remember the expansion as a0 + a1.*x + a2.*x.^2 + ...
Also good to know that reshape is quicker.

댓글을 달려면 로그인하십시오.

Roger Stafford
Roger Stafford 2018년 2월 24일

0 개 추천

Note that you can avoid the necessity of computing powers of x in the following. It works even if x is an array. It should save some computing time.
y = repmat(p(1),size(x));
for k = 2:length(p)
y = y.*x+p(k);
end

카테고리

도움말 센터File Exchange에서 Polynomials에 대해 자세히 알아보기

질문:

2017년 5월 5일

댓글:

2018년 2월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by