function cgai
% main: returns center of gravity for model AI

x = [12; 0; 5; 7; 17; 19; 24; 12; 15; 9; 27; 27; 31; 31; 27];
y = [24; 0; 0; 4; 4;  0;  0;  14; 8;  8; 24; 0;  0;  24; 24];
nodes=[x,y];

elements={[1,2,3],[3,8,1],[4,5,10],[10,5,9],[1,8,6],[6,7,1],[12,13,11],[11,13,14]};
%
s=[];a=[];
for n=1:length(elements);
    e=elements{n};
    t=[nodes(e(1),:);nodes(e(2),:);nodes(e(3),:)];
    % collect cg of elements in matrix length(elements)x2
    s(end+1,:)=cg(t);
    % collect area of elements in column vector 
    a(end+1,:)=area(t);
end 
sa=sum(a);
cgm=dot(s,[a,a])/sa;
%
disp(['Fläche gesamt: ',num2str(sa)]);
disp(['Schwerpunktskoordinate x: ',num2str(cgm(1))]);
disp(['Schwerpunktskoordinate y: ',num2str(cgm(2))]);
    
function cg=cg(t)
% function cg=cg(t)
% returns center of gravity of 2D triangle t
% 
% input of t: corner coordinates, e.g.
% t=[[-1,0];[1,0];[0,3]];
%
  cg=mean(t,1);

function a=area(t)
% function a=area(t)
% returns area of 2D triangle t
% 
% input of t: corner coordinates, e.g.
% t=[[-1,0];[1,0];[0,3]];
%
  a=0.5*cross2D(t(2,:)-t(1,:),t(3,:)-t(1,:));
  
function c2=cross2D(x,y)
% function c2=cross2d(x,y)
% cross product of 2D vectors (magnitude)
% example: x=[1,2];y=[3,4];
  c2=y(2)*x(1)-x(2)*y(1);

