MATLAB: How to assemble Kglobal in a for loop

femfor loop indexingMATLAB

Trying to solve a FEM problem using given data and a for loop to run for each node's stiffness matrix. I think I need to index each K matrix as the loop runs, but currently, I can only get the last variable of K, and it is not indexing into the Kglobal matrix. Any help would be appreciated.
% clc
%%Input Text Files
connectivity_data = dlmread('connectivity.txt');
forces_data = dlmread('forces.txt')';
boundaryconditions_data = dlmread('boundaryconditions.txt');
%%Enter in functions to extract needed rows and columns from .txt files
irow = connectivity_data(:,2);
jcolumn = connectivity_data(:,3);
L = transpose(connectivity_data(:,5));
theta = connectivity_data(:,4);
index = 2*((numel(connectivity_data(:,1)))-1);
nelement = length(connectivity_data(:,4));
%%Enter in degrees of freedom and # of nodes
ndof = 2;
nnodes = (nelement-1);
%%Input Constants needed to solve for connectivity_data matrix
E = 3e7;
A = 4;
EA = E*A;
%%Input Forces
%%Assign a K for each element using formula K=(E*A)/L
% E*A will remain constant, while L will change at each node
% K = (EA)./(in);
%%Establish for loop to calculate Stiffness Matrix for each element
K = zeros(ndof*nnodes)
for (i = 1:nelement)
theta = connectivity_data(i,4);
C = cosd(theta);
S = sind(theta);
U = [C.^2 C.*S -C.^2 -C.*S;
C.*S S.^2 -C.*S -S.^2;
-C.^2 -C.*S C.^2 C.*S;
-C.*S -S.^2 C.*S S.^2 ];
L = connectivity_data(i,5);
K = ((EA)/L)*U;
KG(index,1) = K(1,1);
end

Best Answer

for (i = 1:nelement)
Remove the parentheses.
theta = connectivity_data(i,4);
C = cosd(theta);
S = sind(theta);
U = [C.^2 C.*S -C.^2 -C.*S;
C.*S S.^2 -C.*S -S.^2;
-C.^2 -C.*S C.^2 C.*S;
-C.*S -S.^2 C.*S S.^2 ];
L = connectivity_data(i,5);
K = ((EA)/L)*U;
KG(index,1) = K(1,1);
Where in this loop does the variable index change its value? Did you mean to use i instead of index in determining the element in KG into which to write K(1, 1)?
end