Reputation: 1592
I'm fitting some data, but when I plot the data and fit in one-line-plot (see left figure) the drawn graph is correct
plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
But when I used two separated plot (see right figure) the graph differs from mention above
hold on;
plot(x, y, '.b;data;', [0.05 2]);
plot(phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
hold off;
grid on;
Data
[x, y]
ans =
0.050000 3571.000000
0.100000 6567.000000
0.200000 12760.000000
0.300000 20512.000000
0.400000 25480.000000
0.500000 32088.000000
1.000000 63223.000000
2.000000 128690.000000
Calculate Linear Regression
A = [N, sum(x); sum(x), sum(x.*x)];
b = [sum(y); sum(x.*y)];
phi = inv(A)*b;
Is there any way to solve this?
Upvotes: 0
Views: 460
Reputation: 19689
When the x-axis values are not specified then 1:numel(y)
are considered to be the x-axis values.
In your code:
%Your first graph:
plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
%^^^^^^^
%Your second graph:
plot(x, y, '.b;data;', [0.05 2]);
%^^^^^^^^^
plot(phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
%!!!!!!!!!!!!!!!!!!!!!! %^^^^^^^^^
The parts highlighted with ^
in above plot
commands have x=[1 2]
and y=[0.05 2]
and the part highlighted with !
has x=[1 2]
and y=phi(1)+phi(2)*[0.05 2]
. You can see those lines being drawn if you zoom at that area.
So your first plot command should be:
plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;');
and it should be split like this:
plot(x, y, '.b;data;');
hold on;
plot([0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;');
Upvotes: 2