Evaluate a Polynomial without polyval
11 views (last 30 days)
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;
y(i) = accum+p(i)*xtothepower;
accum = y(i);
Walter Roberson on 5 May 2017
In your line
you are overwriting all of xtothepower each iteration.
Dillen.A on 23 Feb 2018
Edited: Dillen.A on 23 Feb 2018
For anyone still interested in this, my quick solution:
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.
Roger Stafford on 24 Feb 2018
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);