0

I'm building a least-squares solver for an ellipse and then plotting the ellipse on a graph. When I run this code I get the correct graph with no problems.

x = [1.02 0.95 0.87 0.77 0.67 0.56 0.44 0.30 0.16 0.01]
y = [0.39 0.32 0.27 0.22 0.18 0.15 0.13 0.12 0.13 0.15]
V1 = zeros(10, 5) 
for i in 1:length(x) 
    V1[i,1] = y[i]^2 
    V1[i,2] = x[i]*y[i]
    V1[i,3] = x[i]
    V1[i,4] = y[i]
    V1[i,5] = 1
end
display(V1)
xsquared1 = x' .* x'
c = V1\xsquared1
f(x,y) = c[1]*y^2 + c[2]*x*y + c[3]*x +c[4]*y + c[5] - x^2 
x = collect(-1.5: 0.1: 1.5)
y = copy(x)
contour!(x,y,f, levels=[0.0], aspect_ratio=:equal, c=:heat, lw=2)

But when I run this code with a second set of data:

x = [1.02 0.95 0.87 0.77 0.67 0.56 0.44 0.30 0.16 0.01]
y = [0.39 0.32 0.27 0.22 0.18 0.15 0.13 0.12 0.13 0.15]
x1 = x + (rand(10,1)/100 .- 0.005)'
y1 = y + (rand(10,1)/100 .- 0.005)' 
V2 = zeros(10, 5) 
for i in 1:length(x) 
    V2[i,1] = y1[i]^2 
    V2[i,2] = x1[i]*y1[i]
    V2[i,3] = x1[i]
    V2[i,4] = y1[i]
    V2[i,5] = 1
end
xsquared2 = x1' .* x1'
c2 = V2\xsquared2
f2(x,y) = c2[1]*y1^2 + c2[2]*x1*y1 + c2[3]*x1 +c2[4]*y1 + c2[5] - x1^2 
x = collect(-1.5: 0.1: 1.5)
y = copy(x)
contour!(x,y,f2, levels=[0.0], aspect_ratio=:equal, c=:heat, lw=2)

I get an error that reads

DimensionMismatch("A has dimensions (1,10) but B has dimensions (1,10)")

despite every element of the second set having the same dimensions of the first set.

1 Answers1

0

I can confirm what @mcabbott commented, the issue is not your set of data but instead that you have typos in your f2. Using

f2(x1,y1) = c2[1]*y1^2 + c2[2]*x1*y1 + c2[3]*x1 +c2[4]*y1 + c2[5] - x1^2

instead works for me.

Benoit Pasquier
  • 2,868
  • 9
  • 21