MATLAB: Hello, does anybody know why matlab show this error for the line of “Kg(i)” ? error : Subscripted assignment dimension mismatch. (I appreciate if you help me.)

subscripted assignment dimension mismatch

XY=[0 0;0 3.5;0 0;4 0;0 0;4 3.5;0 3.5;4 0;0 3.5;4 3.5;4 3.5;4 0] , elementnumber=6 , A=1 , E=1
for i=1:elementnumber;
L(i)=sqrt((XY(2*i,1)-XY(2*i-1,1))^2+((XY(2*i,2)-XY(2*i-1,2))^2))
theta(i)=atan((XY(2*i,2)-XY(2*i-1,2))/(XY(2*i,1)-XY(2*i-1,1)))*180/pi
c(i)=cosd(theta(i))
s(i)=sind(theta(i))
Kg(i)=A*E/L(i)*[c(i)^2 c(i)*s(i) -c(i)^2 -c(i)*s(i);c(i)*s(i) s(i)^2 -c(i)*s(i) -s(i)^2;-c(i)^2 -c(i)*s(i) c(i)^2 c(i)*s(i);-c(i)*s(i) -s(i)^2 c(i)*s(i) s(i)^2]
end

Best Answer

Your ‘Kg’ calculation creates a new (4x4) matrix in each iteration. Subscript it as:
Kg(:,:,i) = A*E/L(i)*[c(i)^2 c(i)*s(i) -c(i)^2 -c(i)*s(i);c(i)*s(i) s(i)^2 -c(i)*s(i) -s(i)^2;-c(i)^2 -c(i)*s(i) c(i)^2 c(i)*s(i);-c(i)*s(i) -s(i)^2 c(i)*s(i) s(i)^2]
and the error disappears.
Related Question