Asked by Stelios Fanourakis
on 20 Apr 2019

Hi

I have two datasets (X,Y). For every value of Y that corresponds to a value of X.

I am thinking of applying a polyfit command to get the best curve fitting for the data, and as a result I will come up with a function (slope+intercept).

How do I find the difference between those two functions? What command do I apply to subtract Function A from Function B?

Answer by Walter Roberson
on 21 Apr 2019

Accepted Answer

P1 = polyfit((1:length(X)).', X(:), 6);

Likewise for Y producing P2

Pd = polyval(P1, 1:length(X)) - polyval(P2, 1:length(X))

Walter Roberson
on 22 Apr 2019 at 23:54

%after the readtable

mask = isnan(x1{:,:}) | isnan(y1{:,:});

x1(mask,:) = [];

y1(mask,:) = [];

mask = isnan(x2{:,:}) | isnan(y2{:,:});

x2(mask,:) = [];

y2(mask,:) = [];

Stelios Fanourakis
on 23 Apr 2019 at 11:25

I get the below error

P1 =

0 0 0 0 0 0 0

Warning: Polynomial is not unique; degree >= number of data points.

> In polyfit (line 74)

In curvefitdif (line 19)

P2 =

0 0 0 0 0 0 0

Pd =

0×1 empty double column vector

P11 =

0×1 empty double column vector

P22 =

0×1 empty double column vector

Stelios Fanourakis
on 24 Apr 2019 at 1:42

I also get the error

Error using isnan

Too many input arguments.

Error in see (line 38)

mask = isnan(x1{:,:}) | isnan(y1{:,:});

Why?

Sign in to comment.

Answer by John D'Errico
on 21 Apr 2019

Stelios Fanourakis
on 22 Apr 2019

John D'Errico
on 23 Apr 2019 at 12:54

If pdiff gives a result of NaN, then one or both of the polynomials was already garbage. LOOK at the cofficients that you got from those two fits.

NaN can only ever result as a subtraction by things like inf - inf, or anything plus a NaN. So the problem lies in your original fits.

Stelios Fanourakis
on 23 Apr 2019 at 15:49

Actually, the problem lies where I use readtable and import the columns from excel.

They are imported as NaNs

Sign in to comment.

Answer by Stelios Fanourakis
on 21 Apr 2019

John D'Errico
on 21 Apr 2019

Did I not say just how to do that in my answer?

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Walter Roberson (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/457597-how-to-use-polyfit-to-get-the-difference-out-of-two-functions#comment_696337

## Stelios Fanourakis (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/457597-how-to-use-polyfit-to-get-the-difference-out-of-two-functions#comment_696441

Sign in to comment.