 #1
Wrichik Basu
Gold Member
 1,448
 1,301
Main Question or Discussion Point
I have some experimental data, and I would like to plot a graph in matlab and also find the best fit line. I also want to find the distance between each point and the best fit line, and if the distance is greater than 1 unit, an error will be shown.
For this, I have written a function. Here it is:
Matlab gives me a good graph:
The data is:
But all distances of points are coming to be 0. Because the subs(eqn2) is yielding a 0. From the graph, it is evident that all points do not lie on the line. But I'm still getting a 0. I know this because I printed p from the function. This is what I got:
Any help is appreciated. Where am I going wrong?
Any ideas?
I use matlab mobile, version R2018a.
For this, I have written a function. Here it is:
Matlab:
function [] = plot2d(X,Y);
%The aim of this function is to read
% X and Y from the user, and plot the points.
% The best fit line shall be shown.
hold off;
%this plots the given data points
plot(X,Y,'.k', 'MarkerSize', 20);
hold on;
%here, we are calculating the best fit line
p = polyfit(X,Y,1);
f = polyval(p, X);
plot(X, f, 'r');
%necessary plot settings
zoom on;
set(gca, 'xminorgrid', 'on', 'yminorgrid', 'on');
syms x1 y1 x2 y2 x y;
%finding the equation of the best fit line
x1 = X(1);
x2 = X(end);
y1 = f(1);
y2 = f(end);
m = (y2  y1) / (x2  x1);
eqn = y  y1 == m * (x  x1);
%simplifying the equation
eqn = simplify(eqn);
%writing the equation in Ax + By + C = 0 form and removing the rhs to make it an algebraic expression
eqn2 = lhs(eqn)  rhs(eqn);
coefx = coeffs(eqn2,x);
%coefficient of x
cx = coefx(end);
coefy = coeffs(eqn2,y);
%coefficient of y
cy = coefy(end);
%finding number of data points given
sz = numel(X);
for i = 1:1:sz
x = X(i);
y = f(i);
%evaluating the expression by putting in values
p = subs(eqn2);
%calculating final distance
dist = p / sqrt(cx^2 + cy^2);
if dist > 1
disp("Error for point (" + x + "," + y + ")");
end
end
hold off;
end
The data is:
But all distances of points are coming to be 0. Because the subs(eqn2) is yielding a 0. From the graph, it is evident that all points do not lie on the line. But I'm still getting a 0. I know this because I printed p from the function. This is what I got:
Any help is appreciated. Where am I going wrong?
Any ideas?
I use matlab mobile, version R2018a.
Attachments

31.3 KB Views: 383

11.8 KB Views: 266

8.5 KB Views: 251

8.2 KB Views: 268
Last edited: