MATLAB: How to superimpose certain indices of two matrices.

matricesmatrix arraymatrix manipulation

Suppose I have matrices K^1 and K^2. I would like to construct a globla stiffness matrix such that wwe add certain indices to construct the globlal matrix. The color coating indicates the elements being added and their corresponding index in the global matrix. How would I do this in Matlab? How would I do it if I had more matices?

Best Answer

For two matrices, try
K1 = rand(4);
K2 = rand(4);
Kg = zeros(6);
Kg(1:4, 1:4) = K1;
Kg(3:6, 3:6) = Kg(3:6, 3:6) + K2
For a general case
K1 = rand(4);
K2 = rand(4);
K3 = rand(4);
K4 = rand(4);
K = {K1, K2, K3, K4};
n = 2*numel(K)+2;
Kg = zeros(n);
Kg(1:4, 1:4) = K{1};
for i = 2:numel(K)
Kg(2*i-1:2*i+2, 2*i-1:2*i+2) = Kg(2*i-1:2*i+2, 2*i-1:2*i+2) + K{i};
end