代码之家  ›  专栏  ›  技术社区  ›  Artorius

利用三角形面积和计算多边形面积的MATLAB函数

  •  0
  • Artorius  · 技术社区  · 8 年前

    我有一个关于我写的MATLAB函数的问题。它以两行向量的形式将一组x和y顶点坐标作为输入,并使用这些坐标计算多边形的面积。

    使用我为三角形面积创建的函数,可以根据以下步骤计算多边形的面积:

    • 有N-2个三角形(其中N是多边形的边数)

    • (使用 A = 0.5(x1*(y2-y3)-x2*(y1-y3)+x3(y1-y2)

    我的代码写在下面。我的周长函数工作得很好,但我不知道如何将三角形的面积函数实现到多边形面积程序中。 我相信我的公式是正确的,问题在于循环索引的某个地方。

    function [tri_area] = area2dd(coords_x,coords_y)
    
    %%Input argument check
    narginchk(2,2) ;
    
    %%Calculation
    % % ii = 1:length(coords_x)-2;
    % % jj = 1:length(coords_y)-2;
    
    if length(coords_x) == 3 
        ii = 1:length(coords_x) -2;
        jj = 1:length(coords_y) -2;
        tri_area = sum(abs(0.5.*(coords_x(ii).*(coords_y(jj+1)-21coords_y(jj+2))-coords_x(ii+1)... 
            .*(coords_y(jj)-coords_y(jj+2))+coords_x(ii+2).*(coords_y(jj)-23coords_y(jj+1)))))
    else
        ii = 1:3:length(coords_x) -2;
        jj = 1:3:length(coords_y) -2;
        tri_area = sum(abs(0.5.*(coords_x(ii).*(coords_y(jj+1)-29coords_y(jj+2))-coords_x(ii+1)... 
           .*(coords_y(jj)-coords_y(jj+2))+coords_x(ii+2).*(coords_y(jj)-31coords_y(jj+1)))))
    end
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Artorius    8 年前

    好的,对于任何感兴趣的人或任何其他可能正在解决像我这样的问题的人,我有下面编写的最终工作代码。此功能可以执行双重任务。如果输入的坐标向量为3对,则该函数将计算三角形的面积。如果有3组以上的坐标对,则它将计算由这些坐标包围的多边形的面积。

    narginchk(2,2) ;
    if length(coords_x) == 3 
    ii = 1
    jj = 1
    area = sum(abs(0.5.*(coords_x(ii).*(coords_y(jj+1)-coords_y(jj+2))- ...
    coords_x(ii+1).*(coords_y(jj)-coords_y(jj+2))+coords_x(ii+2).*...       
    (coords_y(jj)-coords_y(jj+1))))) ;
    else
    ii = 1:length(coords_x) -3 ;
    jj = 1:length(coords_y) -3 ;
    area = sum((abs(0.5.*(coords_x(1).*(coords_y(jj+1)-coords_y(jj+2)) ...
    -coords_x(ii+1)... 
    .*(coords_y(1)-coords_y(jj+2))+coords_x(ii+2).*(coords_y(1)- ...
    coords_y(jj+1)))))) ;
    end
    end