Best-Fit line only extends in the positive x-axis direction

1 view (last 30 days)
Alright so I've written this piece of code in Matlab with the goal of having a line of best fit plotted in place of my two data arrays so that I can see where the line crosses the x&y axes visually. The only problem is, the line of best fit only extends in the positive x-axis direction, so it never actually crosses the x and y axes. What am I missing?
y = [200 300 400 500]; % Lambda
invy = 1./y; %1/Lambda
V = [4.00 1.86 0.85 0.21]; % Vo
q = 1.6e-19; % Charge of Electron
p = polyfit(invy,V,1);
f = polyval(p,invy);
figure(1)
plot(invy,f)
xlim([-5e-3 5e-3])
ylim([-2 2])
grid on

Accepted Answer

Image Analyst
Image Analyst on 4 Feb 2020
Try this:
y = [200 300 400 500]; % Lambda
invy = 1./y; %1/Lambda
V = [4.00 1.86 0.85 0.21]; % Vo
q = 1.6e-19; % Charge of Electron
hFig = figure;
plot(invy, V, 'b.', 'MarkerSize', 50);
grid on;
hFig.WindowState = 'maximized';
% Determine the coefficients of the line.
coefficients = polyfit(invy, V, 1)
fprintf('Equation of the line is: V = %f * invy + %f.\n', coefficients(1), coefficients(2));
% Now do a fit from -xmax to +xmax, or whatever you want.
xmax = abs(max(invy));
xFit = linspace(-xmax, xmax, 800); % 800 points, or however many you want.
yFit = polyval(coefficients, xFit);
hold on;
plot(xFit, yFit, 'b-', 'LineWidth', 2);
xlim([-xmax, xmax])
xlabel('invy', 'FontSize', 20);
ylabel('V', 'FontSize', 20);
% ylim([-2 2])
grid on;
% Put lines along axes.
xline(0, 'LineWidth', 2, 'Color', 'k');
yline(0, 'LineWidth', 2, 'Color', 'k');
% If you want tick marks inside rather than outside the graph, do this:
ax = gca;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
0001 Screenshot.png

More Answers (0)

Categories

Find more on Graphics Object Properties in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!