Haider
Haider

Reputation: 958

matlab surface fitting not working a per expectation

I have tried matlab's curve fitting which works well, but in case of surface fitting matlab is disregarding the second independent variable. Below is an example that replicates the problem.

function curve_fitting_test()
x1 = (1:100)';
x2 = (1:100)';
y = 10.*x1 + 20.*x2 + 30;
ft = fittype(@(a,b,c,x1,x2)a.*x1 + b.*x2 + c, 'independent', {'x1', 'x2'});
cf = fit([x1 x2], y, ft, 'start', [25 25 25], 'Lower', [0 0 0], 'Upper', [50 50 50])

This is the model which matlab is generating:

General model:
cf(x1,x2) = a.*x1+b.*x2+c
Coefficients (with 95% confidence bounds):
a =          15  (15, 15)
b =          15  (15, 15)
c =          30  (30, 30)

Upvotes: 0

Views: 134

Answers (1)

nkjt
nkjt

Reputation: 7817

The problem is your input:

x1 = (1:100)';
x2 = (1:100)';
y = 10.*x1 + 20.*x2 + 30;

y is only calculated for the cases where x1 = x2 here, not all combinations. Therefore, anything from y = 30.*x1 + 30 to y = 30.*x2 + 30 would be acceptable as long as a + b = 30. You can see this by plotting your original data (black points) vs. the fit - the fit that MATLAB finds is perfectly acceptable for the data it has been given:

fit surface vs original data

The solution is to change your data input. For example, just by changing x1 and x2 to random integers between 1 and 100, with all other code the same:

x1 = randi(100,100,1);
x2 = randi(100,100,1);

After fitting gives me:

 General model:
     cf(x1,x2) = a.*x1+b.*x2+c
     Coefficients (with 95% confidence bounds):
       a =          10  (10, 10)
       b =          20  (20, 20)
       c =          30  (30, 30)

Upvotes: 2

Related Questions