I see that you did not define "L" in the code. Assuming that "L" is the length of elements,I modifed the code. You can try it.
clc;
clear;
disp('Global Stiffness Matrix for a 2 noded 1-D element');
n = input('Enter the number of elements: ');
A = input('Enter the cross-sectional area of the element in mm^2: ');
E = input('Enter the Youngs Modulus of the element in N/mm^2: ');
% Initialize arrays for node coordinates
x = zeros(1, n+1); % Assuming linear elements, n+1 nodes
% Input node coordinates
for i = 1:n+1
x(i) = input(['Enter x coordinate of node ', num2str(i), ': ']);
end
% Initialize global stiffness matrix
Kg = zeros(n+1);
% Element stiffness matrix calculation and assembly into global matrix
for i = 1:n
% Length of the element
L = abs(x(i+1) - x(i));
% Local stiffness matrix for the current element
k_local = (A*E/L)*[1 -1; -1 1];
% Assembly into global stiffness matrix
Kg(i:i+1, i:i+1) = Kg(i:i+1, i:i+1) + k_local;
end
disp('The global stiffness matrix is:');
disp(Kg)
