Info

This question is closed. Reopen it to edit or answer.

Least Squares Of Linear Equations

1 view (last 30 days)
Harel Harel Shattenstein
Harel Harel Shattenstein on 3 Jul 2018
Closed: MATLAB Answer Bot on 20 Aug 2021
P=mt/b+t iff P=m-b*P\t
t=transpose([1 3 4 7 8 10]);
P=transpose([2.1 4.6 5.4 6.1 6.4 6.6]);
A=[ones(length(p),1), -P./t];
At=transpose([ones(length(P),1),-P./t]);
V=inv(At*A)*(At*P);
m=V(1)
b=V(2)
Now to find the plot I used:
x=P/t;
f=@(x)m-b.*(x);
plot(t,P,'.')
hold on
plot(t,f(t))
Which seems incorrect

Answers (1)

David Goodmanson
David Goodmanson on 3 Jul 2018
Edited: David Goodmanson on 3 Jul 2018
Hi HH,
There are a a couple of things going on here. I compacted your code a bit to make the code below, using .' in place of the transpose commands. It appears your values for P are not an exact fit, nothing wrong with that.
For the fitting plot, you need to use f(x) or f(P./t), not f(t). Also, you meant x = P./t not x = P/t. After that you get the correct plot.
At least as important, you are using the old fashioned normal-matrix technique with inv(A.' * A) to find V. That's all right accuracywise for a 2x6, but it is not good practice in general.
You want to solve
P = A*V
for V, where P and V are column vectors. In Matlab, the solution is simply
V = A\P
(The idea is that you are effectively dividing P on the left by A).
For large arrays, backslash is more accurate than the normal-matrix approach, and there is no need to compute an inverse. Besides, backslash is how Mathworks got its start.
t = [1 3 4 7 8 10].';
P = [2.1 4.6 5.4 6.1 6.4 6.6].';
A = [ones(size(P)), -P./t];
% At=transpose([ones(length(P),1),-P./t]);
% V=inv(At*A)*(At*P);
V = A\P;
% method 1
m = V(1)
b = V(2)
x = P./t;
f = @(x)m-b.*(x);
figure(1)
plot(t,P,'.-',t,f(P./t),'o-')
APPENDED: As far as checking the result, you already have what you need in A and the solved-for V, so an even better way is to replace method 1 with
Pfit = A*V;
figure(1)
plot(t,P,'.-',t,Pfit,'o-')
  1 Comment
Harel Harel Shattenstein
Harel Harel Shattenstein on 3 Jul 2018
Hi, sorry It did not attach the qeustion now it is easier to see where I got it wrong

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by