0

I am currently working on an engineering project and have to use complex numbers. I want to take the complex numbers, plot the real and imaginary parts of them, and then fit a line of best fit that is forced through the origin. This is the following code I have tried (using forums):

close all
clear all
clc

x = [2, -1]; % real parts
y = [1, 6]; % imaginary parts


    for i = 1 : length(x);

    plot([0, x(i)],[0, y(i)] ,'-k', 'LineWidth', 2)
    hold on

    end

hold on

plot(x,y, 'sk', 'Markersize', 10)
yline(0, ':k')
xline(0, ':k')
xlabel('Real axis')
ylabel('Imaginary axis')


x1 = linspace(-10,10,100);

a = x'\y';

y1 = a * x1;

plot(x1, y1, 'r')

For some combination of complex numbers, the line of best fit looks ideal. However, like in this case, the graph gives me the following that does not satisfy my requirement:

enter image description here

Ideally, the line should go through the middle of both of the points. Any help would be greatly appreciated. I have just realised that the reason why is because the y intercept has been 'moved' down but I am still unsure on another method.

Thanks! :)

jammyjam
  • 1
  • 1
  • https://stats.stackexchange.com/questions/54794/regression-through-the-origin – Nigel Apr 21 '22 at 20:21
  • 2
    You say you want _fa line of best fit_. How do you define "best fit" exactly? The operation you are doing minimizes the sum of squared errors when predicting the _y_ values with the red line for the given _x_ values. In your example you get `a = -0.8`. Check that this `a` minimizes the error, by trying different values of `a`: `a = -2:.1:1, err = [sum(abs(a(:).*x-y).^2, 2)]; plot(a, err)` – Luis Mendo Apr 21 '22 at 22:19
  • `"the line should go through the middle of both of the points"` How can it possibly go through the middle of both points and the origin, whilst remaining linear? That's 3 points which aren't colinear on a straight line, not possible. Can you [edit] the question to draw on your plot (an appoximation of) the expected/desired line? – Wolfie Apr 22 '22 at 07:55

0 Answers0