MATLAB: Could you please convert it into a loop

convert into a loop

very simple logic but im not getting
n=4
K = [ 1, 2; 3, 4]
K1=zeros(n+1);
K1([1 2],[1 2])=K
K2=zeros(n+1);
K2([2 3],[2 3])=K
K3=zeros(n+1);
K3([3 4],[3 4])=K
K4=zeros(n+1);
K4([4 5],[4 5])=K
L=K1+K2+K3+K4;
how to convert this into loop where we can add more Kn matrices

Best Answer

In addition to what Stephen said, it's very easy to create your L for any n, without even a loop:
K = [1 2; 3 4];
n = 5;
L = toeplitz([trace(K), K(2, 1), zeros(1, n-2)], [trace(K), K(1, 2), zeros(1, n-2)]);
L([1, end]) = K([1, end])