Solving Tutorial > Task 2–3: Nonlinear Least Squares Fitting
  
Task 2–3: Nonlinear Least Squares Fitting
Fit the parameters of a function that models a data set. Use a solve block to minimize the residuals between the data set and the fitted function. As with other optimization problems, you can also rearrange the problem to look for a root. Here, set the residuals to zero.
1. Define a data set.
Click to copy this expressionClick to copy this expression
2. Define a fitting function, the Weibull, with unknown parameters α and β.
Click to copy this expression
3. Define the residuals, the difference between the v values from the data set and the v values calculated with Wb.
Click to copy this expression
4. Define the sum of squares.
Click to copy this expression
5. To find the parameters α and β that best fit the Weibull function, insert a solve block, define guess values for α and β, and then call the minimize function.
Click to copy this expression
6. Evaluate the solution.
Click to copy this expression
7. Calculate the mean squared error. This value is zero when a true solution exists.
Click to copy this expression
Click to copy this expression
8. Plot the data set and the fitted Weibull function.
Click to copy this expression
Click to copy this expression
9. To fit the parameters using the constraint resid = 0, use the minerr function instead of the minimize function.
Click to copy this expression
You cannot use the find function here because there is no exact solution for α2 and β2. An error is returned to indicate that no solution exists. The minerr function works the same way as the find function, except that it returns an approximate solution if it fails to converge to the solution within a set number of iterations.
10. Calculate the mean squared error for the new parameters.
Click to copy this expression
11. Compare the results returned by minimize and by minerr.
Click to copy this expression
Practice
Before you move on to the next exercise, find the price for an item assuming that you want to maximize profit, n ∙ p. The relationship between the number of items sold and the price is described by the function n:
Click to copy this expression
Plot the profit function for 0 < p < 10 before choosing a guess value.
Proceed to Exercise 3.