MATLAB: Am I getting the error: “Error using + Matrix dimensions must agree.”

error using *forglobal stiffness matrixloopmatrix dimensions must agree

Hello,
I am trying to create a 21×21 global stiffness matrix that look like this:
K = [1 -1 0 0 0...;
-1 2 -1 0 0...;
0 -1 2 -1 0...;
0 0 -1 2 -1...
...]
This is my code so far:
% Define number of nodes
N = 21;
k1 = [1 -1; -1 1];
% Define global stiffness matrix with zeros
K = zeros(N);
% Populate diagonal of matrix, making sparse matrix
for i = 1:(N-1)
for j = 2:N
K(i:j,i:j) = K(i:j,i:j) + k1
end
end
However, I am getting error:
Error using +
Matrix dimensions must agree.
Error in Untitled2 (line 16)
K(i:j,i:j) = K(i:j,i:j) + k1
The dimensions of the matrices that are being added are both 2×2 in every iteration so I do not understand why the loop stops after the first iteration. Any suggestions?
I have written the code for each iteration manually just to double check and the I end up with the correct solution. However, I want to know why the for loop solution is not working. Here is the code for the manual iterations:
K(1:2,1:2) = K(1:2,1:2) +k1
K(2:3,2:3) = K(2:3,2:3) +k1
K(3:4,3:4) = K(3:4,3:4) +k1
K(4:5,4:5) = K(4:5,4:5) +k1
K(5:6,5:6) = K(5:6,5:6) +k1
....
I appreciate the help in advance.

Best Answer

I realized that I misunderstood the the nested for loop for a little while. I ended up figuring it out with a single for loop. For those that are curious and need help with a similar problem, this is my code. I'm sure this is a very inefficient way to solve the problem but its simple enough for me to understand as I am a beginner.
% Define number of nodes
N = 21;
% Define global stiffness matrix with zeros
K = zeros(N);
% Define local stiffness matrix
k1 = [1 -1; -1 1];
% Populate diagonal of global stiffness matrix
for i = 1:N-1
K(i:i+1,i:i+1) = K(i:i+1,i:i+1) + k1;
end