%%%% assemble.m %%%%%
% This is the script file which will compute the local stiffness and mass 
% matrices and will assemeble them assemble. 
% This uses structures node and elem with element and node data as global
% variables and sets the KG and MG, the assembled global matrices.
global node elem KG KSig
j=size(node);
j=j(2);                % number of nodes
m=size(elem);          % number of elements
m=m(2);
KSig=sparse(zeros(3*j,3*j));
KG=sparse(zeros(3*j,3*j));
for i=1:m
    id1=elem(i).end1;
    id2=elem(i).end2;
    x1=node(id1).x;
    y1=node(id1).y;
    x2=node(id2).x;
    y2=node(id2).y;  
    L=sqrt((x2-x1)^2+(y2-y1)^2);   
    A=elem(i).A;
    E=elem(i).E;
    I=elem(i).I;    
    t1=A*E/L;
    t2=12*E*I/L^3;
    t3=6*E*I/L^2;
    t4=4*E*I/L;
%     Rotation matrix for transformation to global co-ordinates
    c=(x2-x1)/L;
    s=(y2-y1)/L;
    R=sparse([  c     s    0;
                -s    c    0;
                0     0    1]);

    % Computes the elements of the Local stiffness matrix
    k11=sparse([t1     0       0;
        0      t2      t3;
        0      t3      t4]);
    k12=sparse([-t1     0     0;
        0      -t2     t3;
        0      -t3     t4/2]);
    k22=sparse([t1      0       0;
        0       t2     -t3;
        0       -t3     t4]);
    % Computes the elements of the Local mass matrix
    m11 = 1/L/30*sparse(   [ 0      0         0;
        0         36        3*L;
        0         3*L       4*L^2]);
    m12 = 1/L/30*sparse( [0       0          0;
        0         -36       3*L;
        0         -3*L     -L^2]);
    m22=  1/L/30*sparse([ 0       0          0;
        0     36       -3*L;
        0     -3*L      4*L^2]);

    % Computing the values in the global stiffness matrix for the element
    mg11=R*m11*R';
    mg12=R*m12*R';
    mg22=R*m22*R';
    id11=3*id1-2:3*id1;
    id22=3*id2-2:3*id2;
    KSig(id11,id11)=KSig(id11,id11)+m11;
    KSig(id11,id22)=KSig(id11,id22)+m12;
    KSig(id22,id11)=KSig(id22,id11)+m12';
    KSig(id22,id22)=KSig(id22,id22)+m22;

    % Computing the values in the global stiffness matrix for the element

    kg11=R*k11*R';
    kg12=R*k12*R';
    kg22=R*k22*R';


    % Assembling the Global stiffness Matrix
    id11=3*id1-2:3*id1;
    id22=3*id2-2:3*id2;
    KG(id11,id11)=KG(id11,id11)+kg11;
    KG(id11,id22)=KG(id11,id22)+kg12;
    KG(id22,id11)=KG(id22,id11)+kg12';
    KG(id22,id22)=KG(id22,id22)+kg22;
end