I want to curve fit the straight line equation:
$$ y = kx + m$$
Where $k$ is the slope and $x$ is the variable and $m$ is where it cuts onto the y-axis.
So assume that we have a plot who looks like this:
Code:
R = 1:50;
Y = R.*rand(1, 50);
plot(Y);
And I want to find the best fit by minimizing this cost function:
$$V(k,m) = \sum(Y - \hat{Y})^2 = \sum(Y-(kx + m))^2$$
So how can I find my best $k$ and best $m$ which minimize the cost function $V(k,m)$ ?
I want to solve this with a for-loop.

Here is the answer. I can't believe that all mathematics about linear regression was so difficult and hard explained, and my answer is the easiest one and does the job!
The estimated line of best fit
The line is about
$$y = 0.25x + 0.4$$
The cost function
The code: