MATLAB: Assemble global stiffness matrix

hamani

I am trying to assemble a matrix in which I would like to put small matrices into a big one but I don't know how to do that,
I know that I have to define the big matrix first and then show put the small ones inside
for example I have k1=[1 -1; -1 1] , K2=[1 -1; -1 1] and the define bigK in which bigK=zeros(3,3) and in the end I want it to be like bigK = [ 1 -1 0; -1 2 -1; 0 -1 1]
in which the small matrices will assemble in diagonal way
how I can do it using a for loop ?

Best Answer

K = zeros(10,10);
k = [1 -1; -1 1];
for n = 1:9;
rind = n + [0 1];
cind = rind;
K(rind, cind) = K(rind, cind) + k;
end
There are better ways to do this in terms of pure efficiency. But the above will suffice. First learn how to write at least decent code that solves the task at hand. Only when you decide if the code is a problem do you want to worry about optimizing it for speed.