obizues
obizues

Reputation: 1473

How do I find Multiple Roots for a Polynomial in Matlab?

I'm trying to create two matlab .m files. "f.m" contains a function of the polynomial I want to use.

function y = f(x)
y = x.^3 - 7*x + 6;

Compute.m calls fzero with that function returning the polynomial and a for loop of values from -10 to 10.

clc
fun = @f;
answerArray= [];
for x0 = -10:10
    z = fzero(fun,x0);
    answerArray=[answerArray z];
end
answerArrayUnique=unique(answerArray)

The problem is my unique method is not working for some of the negative values. I am getting an answer of:

answerArrayUnique =

-3.0000 -3.0000 -3.0000 1.0000 2.0000

What is strange, is that if unique was failing every time on negative numbers there would be many more -3.0000's. Anyone have any idea what is causing this?

Note: Using the unique method call on that again does not fix the issue, which leads me to believe it thinks the numbers as they go further out in to the ten-thousandth spot are different.. maybe?

Upvotes: 0

Views: 551

Answers (2)

Nicky Mattsson
Nicky Mattsson

Reputation: 3052

You should see Mendis answer, for how to properly do it. However, the problem you have is because those -3.000 are not equal.

unique work by sorting and then checking if consecutive numbers are equal. However, as you have used a numerical method to find the zeros, the solutions are approximate. Try to subtract two of the equal solutions, the difference will be small, but not zero.

To avoid this you can use uniquetol which allows you to specify a tolerance, for which within, you think two numbers are equal. e.g. uniquetol(answerArray,1e-4)

Upvotes: 1

Mendi Barel
Mendi Barel

Reputation: 3677

In matlab the best way to represent a polynomialy is thru coefficient vector. for your example:

p = [1 0 -7 +6];

To calculate the value at x=0.8 for example you use:

polyval(p,0.8)

to find the roots you use:

r = roots(p) %output: -3 2 1

Use 'fzero' only for non linear function and pray to find all solutions.

Upvotes: 0

Related Questions