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.
However, I assume that you have to use a loop for your assignment.
you are overwriting all of xtothepower each iteration.
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.
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.
Also good to know that reshape is quicker.
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.