MATLAB: Finite Elements Method creating global stiffness matrix

change valueelementfemfiniteloopMATLABmatrixmethodnodestiffness

Hi everyone, I am really stuck in creating a code that creates global stiffness matrix that changing local stiffness matrixes value in every cycle.
For example it has to be
k1 -k1 0 0
-k1 k1+k2 – k2 0
0 – k2 k2+k3 -k3
0 0 -k3 k3
but my code doesn't change k1 to k2 for next step … it only calculates for k1.
k1 -k1 0 0
-k1 k1+k1 – k1 0
0 – k1 k1+k1 -k1
0 0 -k1 k1
Please help me to solve this problem. Thanks.
clear
tp=[1 2]
for i=2:4
tp(i,:)=tp(i-1,:)+1
end
tpmax=max(max(tp));
KG=zeros(tpmax,tpmax);
for i=1:4
d(i)=32+(28/1200)*(2*i-1)*50
G(i)=(77000*pi*d(i).^4)/3200
k=[G(i) -G(i);-G(i) G(i)]
end
for n=1:4
i=n+[0 1]
j=i
KG(i,j)=KG(i,j)+k
end

Best Answer

Hi,
you overwrite k every time. Im sure it could be done much easier - but here s a quick solution without any code optimization (Matlab users usually try to avoid for loops...):
clear
tp=[1 2];
for i=2:4
tp(i,:)=tp(i-1,:)+1;
end
tpmax=max(max(tp));
KG=zeros(tpmax,tpmax);
for i=1:4
d(i)=32+(28/1200)*(2*i-1)*50;
G(i)=(77000*pi*d(i).^4)/3200;
k(:,:,i)=[G(i) -G(i);-G(i) G(i)];
end
for n=1:4
i=n+[0 1];
j=i;
KG(i,j)=KG(i,j)+k(:,:,n);
end
Result is:
KG =
1.0e+08 *
0.9147 -0.9147 0 0 0
-0.9147 2.1154 -1.2006 0 0
0 -1.2006 2.7494 -1.5488 0
0 0 -1.5488 3.5165 -1.9677
0 0 0 -1.9677 1.9677
I think this is what you expected.
Best regards
Stephan