Group Abstract Group Abstract

Message Boards Message Boards

0
|
30 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

How to use LeastSquares[] or QRDecomposition[] to Fit y = mx + b

Posted 20 hours ago

I am trying to calculate the m and b values as a best fit to the equation of the line of y=mx + b - see attached notebook.

In the first section of the notebook, I performed the detail calculations manually to obtain the variables of m = 1.1 and b = 1 to create the equation of the line of y = 1.1x + 1.

Then I tried to use two Mathematica functions (QRDecomposition[] and LeastSquares[]) in an attempt to streamline the calculations and ran into problems. I tried to use examples in both Mathematica as well as examples in the WolframU course on Linear Algebra in which I managed to thoroughly confuse myself because none of the new calculations even remotely resembles the calculations or the end results that I performed manually.

If there is one, I would certainly appreciate someone showing me the recommended method of using Mathematica functions to perform the calculations that I performed manually in the first section of the attached notebook.

Thank you,

Mitch Sandlin

Attachments:
POSTED BY: Mitchell Sandlin
2 Replies

You can do it with Minimize or FindFit:

y = {2, 3, 5, 5};
x = {{1, 1}, {2, 1}, {3, 1}, {4, 1}};
\[Beta] = {m, b};
Minimize[(y - x . \[Beta]) . (y - x . \[Beta]), {m, b}]
data = Transpose[{x[[All, 1]], y}];
Block[{x}, FindFit[data, m*x + b, {m, b}, x]]
POSTED BY: Gianluca Gorni

Here's how I would do it. (I made up my own data vecs xx, yy.)

xx = Subdivide[0., 5., 10];
yy = 1 + 1.1*xx + 
   RandomVariate[NormalDistribution[0., 0.2], Length@xx];
design = Transpose@{ConstantArray[1., Length@xx], xx};
bmvec = LeastSquares[design, yy]
(*  {0.936894, 1.11642}  *)

{qq, rr} = QRDecomposition[design];
LinearSolve[rr, qq . yy]
(*  {0.936894, 1.11642}  *)

ListPlot[Transpose[{xx, yy}], 
 Epilog -> {Red, Line[{{0, Last[bmvec]}, {5, bmvec . {1, 5}}}]}]

data and best-fit line

POSTED BY: Michael Rogers
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard