Polyval/Polyfit input values

3 views (last 30 days)
Sophie Song
Sophie Song on 23 Apr 2016
Edited: Image Analyst on 23 Apr 2016
Hi, I'm new to MatLab and I've been attempting to use Polyval/Polyfit.
The code resembles something like this:
xmin=5;
xmax=100;
xrange = xmin:xmax;
p = [6 2 4 1 1];
polyval(p, xrange)
For some reason, the above results in a list of return values that are not in numerical order. In other words, the y values calculated using polyval are not all in the order that they should be in. Sporadically there are negative values outputted in the return between positive values.
For the function y=6x^4 + 2x^3 + 4x^2 + x + 1 where all my input values are positive, this theoretically should not be the case.
It is also interesting to note that if I instead insert xmin and xmax directly into the polyval parameters, the return values are in correct order.
Anyone ever run into a similar problem?
Thanks!
  1 Comment
Are Mjaavatten
Are Mjaavatten on 23 Apr 2016
When I enter your code into Matlab I get nice positive values that increase monotonically, as expected. Could it be that you have accidentally redefined polyval? Try
which polyval
This should result in something like
C:\Program Files\MATLAB\R2014b\toolbox\matlab\polyfun\polyval.m
If you get a very different answer, enter the command
clear polyval
to revert to the original behaviour.

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 23 Apr 2016
Sorry, but this is a common problem that people have, who are just learning to use MATLAB. That is, as a novice, one tends not to be careful about knowing exactly what is in their variables.
xmin=5;
xmax=100;
xrange = xmin:xmax;
p = [6 2 4 1 1];
yhat = polyval(p, xrange);
all(yhat > 0)
ans =
1
all(diff(yhat) > 0)
ans =
1
As you can see, all the values of yhat are positive, and they are in strictly increasing order.
The point is, you have done something wrong. You may have stuffed the wrong coefficients into the vector p that contains those polynomial coefficients, and done so without realizing what you have done. Again, this is a common error.
Of course, you tell us only that the code "resembles" what you show. So you may have done something entirely else equally wrong. But how can I guess?
  1 Comment
Sophie Song
Sophie Song on 23 Apr 2016
Thank you, I will attempt to look at my code some more and do what both you and Are have suggested.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 23 Apr 2016
Edited: Image Analyst on 23 Apr 2016
This works fine:
xmin=5;
xmax=100;
xrange = xmin:xmax;
p = [6 2 4 1 1];
y=polyval(p, xrange)
plot(xrange, y, 'b*-')
grid on;
No negatives, and nothing out of order. Demos attached.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!