0

如何编写具有 3 个输入(由系数 [abc] 和 x 值向量组成的 2 个向量)的函数,该函数具有两个形式为 ax+by=c 的线方程,输出一个向量,给出交点的 x 和 y 值。

示例:solveSystem([1 -1 -1],[3 1 9],-5:5 ) 应该产生 [2 3]

至今:

function coeff=fitPoly(mat)

% this function takes as an input an nx2 matrix consisting of the
% coordinates of n points in the xy-plane and give as an output the unique
% polynomial (of degree <= n-1) passing through those points.


[n,m]=size(mat);  % n=the number of rows=the number of points
% build the matrix C
if m~=2
    fprintf('Error: incorrect input');
    coeff=0;
  else
  C=mat(:,2);  % c is the vector of y-coordinates which is the 2nd column of mat

  % build the matrix A
  for i=1:n
    for j=1:n
        A(i,j)=(mat(i,1))^(n-j);
    end
end
coeff=inv(A)*C;
end
4

1 回答 1

2

您不需要向量 x 来求解两条线的交点:

function xy = solve(c1,c2)
  A = [c1(1:2); c2(1:2)];
  b = [c1(3); c2(3)];
  xy = A\b;
end

这将计算

xy = solve([1 -1 -1],[3 1 9])

矩阵

A = [1 -1;
     3 1]
b = [-1
     9]

以便

xy = A^-1 b = [2
               3]
于 2011-12-07T06:16:20.433 回答