首页 > 解决方案 > Julia 轮廓尺寸不匹配

问题描述

我正在为椭圆构建一个最小二乘求解器,然后在图形上绘制椭圆。当我运行这段代码时,我得到了正确的图表,没有任何问题。

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)

但是当我用第二组数据运行这段代码时:

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)

我收到一条错误消息

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

尽管第二组的每个元素都具有与第一组相同的尺寸。

标签: julialeast-squaresplots.jl

解决方案


我可以确认@mcabbott 评论了什么,问题不是您的数据集,而是您的f2. 使用

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

相反对我有用。


推荐阅读