首页 文章

在MATLAB中绘制二阶方程的解

提问于
浏览
1

你能帮我解决下面这个问题:我想解决一个带有两个未知数的二阶方程,并用结果绘制一个椭圆 . 这是我的功能:

fun = @(x) [x(1) x(2)]*V*[x(1) x(2)]'-c

V is 2x2 对称矩阵, c 是一个正常数,有两个未知数, x1x2 . 如果我使用fsolve求解方程,我注意到解决方案对初始值非常敏感

fsolve(fun, [1 1])

是否有可能在不提供精确起始值的情况下获得此方程的解,而是提供范围?例如,我想看到 x1, x2 \in (-4,4) 的可能组合

使用 ezplot 我获得了所需的图形输出,但不是方程的解 .

fh= @(x1,x2) [x1 x2]*V*[x1 x2]'-c;
ezplot(fh)
axis equal

有没有办法让两者都有?非常感谢!

1 回答

  • 3

    你可以从 ezplot 获取 XDataYData

    c = rand;
    V = rand(2);
    V = V + V';
    fh= @(x1,x2) [x1 x2]*V*[x1 x2]'-c;
    h = ezplot(fh,[-4,4,-4,4]); % plot in range
    axis equal
    fun = @(x) [x(1) x(2)]*V*[x(1) x(2)]'-c;
    X = fsolve(fun, [1 1]); % specific solution
    hold on;
    plot(x(1),x(2),'or');
    % possible solutions in range
    x1 = h.XData;
    x2 = h.YData;
    

    或者您可以使用向量输入 fsolve

    c = rand;
    V = rand(2);
    V = V + V';
    x1 = linspace(-4,4,100)';
    fun2 = @(x2) sum(([x1 x2]*V).*[x1 x2],2)-c;
    x2 = fsolve(fun2, ones(size(x1))); 
    % remove invalid values
    tol = 1e-2;
    x2(abs(fun2(x2)) > tol) = nan;
    
    plot(x1,x2,'.b')
    

    然而,最简单和最直接的方法是以二次方程形式重新排列椭圆matrix form

    k = rand;
    V = rand(2);
    V = V + V';
    a = V(1,1);
    b = V(1,2);
    c = V(2,2);
    % rearange terms in the form of quadratic equation:
    %     a*x1^2 + (2*b*x2)*x1 + (c*x2^2) = k;
    %     a*x1^2 + (2*b*x2)*x1 + (c*x2^2 - k) = 0;
    x2 = linspace(-4,4,1000);
    A = a;
    B = (2*b*x2);
    C = (c*x2.^2 - k);
    % solve regular quadratic equation
    dicriminant = B.^2 - 4*A.*C;
    x1_1 = (-B - sqrt(dicriminant))./(2*A);
    x1_2 = (-B + sqrt(dicriminant))./(2*A);
    x1_1(dicriminant < 0) = nan;
    x1_2(dicriminant < 0) = nan;
    % plot
    plot(x1_1,x2,'.b')
    hold on
    plot(x1_2,x2,'.g')
    hold off
    

相关问题