function [K] = fem2D
% function [K] = fem2D
% A 2D FEM code for linear triangles. Return Stifness matrix
% Universidad de Zaragoza - 2015
global coords triangles E nu behaviour
dof = 2; % Degree of freedom per node
numNodes = size(coords,1); numTriang = size(triangles,1);
%
% ALLOCATE MEMORY
%
K = zeros(dof*numNodes);
%
% MATERIAL AND BEHAVIOUR
%
G = E/2/(1+nu);
if behaviour==2 % Plane Strain
    E1 = E*(1-nu)/(1+nu)/(1-2*nu); 
    E2 = E*nu/(1+nu)/(1-2*nu);
elseif behaviour==1 % Plane Stress
    E1 = E/(1-nu^2); 
    E2 = E*nu/(1-nu^2);
end
D = [E1 E2 0;E2 E1 0;0 0 G]; % Behaviour matrix
% Integration points: 3 Hammer Points
sg(1) = 1.0/6.0; sg(2) = 1.0/6.0; sg(3) = 2.0/3.0;
sg(4) = 1.0/6.0; sg(5) = 1.0/6.0; sg(6) = 2.0/3.0;
wg(1) = 1.0/6.0; wg(2) = 1.0/6.0; wg(3) = 1.0/6.0;
nph = numel(wg);
%
% ELEMENT LOOP
%
for j=1:numTriang
    tri = triangles.ConnectivityList(j,:); % Connectivity of each Element
    vertices = coords(tri,:); % Coordinates of the nodes
    Ind = [2*(tri-1)+1; 2*tri]; Ind = Ind(:);
    %
    % JACOBIAN
    %
    a = vertices(2,1)-vertices(1,1); b = vertices(3,1)-vertices(1,1);
    c = vertices(2,2)-vertices(1,2); d = vertices(3,2)-vertices(1,2);
    jcob = a*d - b*c;
    a1 = vertices(2,1)*vertices(3,2) - vertices(2,2)*vertices(3,1);
    a2 = vertices(3,1)*vertices(1,2) - vertices(3,2)*vertices(1,1);
    a3 = vertices(1,1)*vertices(2,2) - vertices(1,2)*vertices(2,1);
    b1 = vertices(2,2) - vertices(3,2); b2 = vertices(3,2) - vertices(1,2);
    b3 = vertices(1,2) - vertices(2,2);
    c1 = vertices(3,1) - vertices(2,1); c2 = vertices(1,1) - vertices(3,1);
    c3 = vertices(2,1) - vertices(1,1);
    %
    % INTEGRATION POINTS LOOP
    %
    chiG = 0.0; etaG = 0.0;
    for j1=1:nph
        chi = sg(2*(j1-1)+1); eta = sg(2*j1);
        %
        % GLOBAL GEOMETRICAL APPROXIMATION
        %
        SHPa(3) = eta; SHPa(2) = chi; SHPa(1) = 1.-chi -eta;
        for k1=1:3
            chiG = chiG + SHPa(k1)*vertices(k1,1);
            etaG = etaG + SHPa(k1)*vertices(k1,2);
        end
        %
        % COMPUTE SHAPE FUNCTIONS AND THEIR DERIVATIVES
        %
        SHP(1) = (a1+b1*chiG+c1*etaG)/jcob; dSHPx(1) = b1; dSHPy(1) = c1;
        SHP(2) = (a2+b2*chiG+c2*etaG)/jcob; dSHPx(2) = b2; dSHPy(2) = c2;
        SHP(3) = (a3+b3*chiG+c3*etaG)/jcob; dSHPx(3) = b3; dSHPy(3) = c3;
        %
        % N AND B MATRIX
        %
        B = [dSHPx(1) 0 dSHPx(2) 0 dSHPx(3) 0; ... 
            0 dSHPy(1) 0 dSHPy(2) 0 dSHPy(3); ...
            dSHPy(1) dSHPx(1) dSHPy(2) dSHPx(2) dSHPy(3) dSHPx(3)];
        %
        % STIFNESS MATRIX
        %
        K(Ind,Ind) = K(Ind,Ind) + B'*D*B/jcob*wg(j1);
    end
end
return
