MATLAB: What is wrong with the for loop

for loopindexingMATLAB

%check for stitching global nxn matrix
elements = 4;
nodes = 5; %nodes
s=3; %size of matrix nxn
k=[1 1 1; 1 1 1; 1 1 1];
size = (s* elements) - (elements-1);
K = zeros(size,size);
K(1:s,1:s) = k(1:s,1:s);
%this fills the matrix with values
for i =2:elements-1
% K((s:((i*s)-(i-1))), (s:((i*s)-(i-1)))) = k(1:s,1:s);
for j = 1:elements-1
K((j*s-j-1):(i*s-i-1), (j*s-j-1):(i*s-i-1)) = k(1:s,1:s);
end
% K((s:((2*s)-(2-1))), (s:((2*s)-(2-1)))) = k(1:s,1:s);
% K((s:((3*s)-(3-1))), (s:((3*s)-(3-1)))) = k(1:s,1:s);
%K(s:((j*s)-(j-1)),s:((j*s)-(j-1))) = k(1:s,1:s);
% K(s:5,s:5) = k(1:s,1:s);
% K(5:7,5:7) = k(1:s,1:s);
% K(7:9,7:9) = k(1:s,1:s);
end
%this adds matrix elements at stitching location
for i = 1:elements-1
K(((i*s)-(i-1)), ((i*s)-(i-1))) = k(1,1)+k(s,s);
end
K
the lines including K(s:5,s:5) to K(7:9,7:9) was my verification to see if the matrix was right and it is. the code above in the for loops should give me the same answers as these but I keep getting an error saying unable to perform assignment because the size of the left matrix doesnt match the right
this is the error I recieve:
Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is
3-by-3.

Best Answer

elements = 4;
s=3; %size of matrix nxn
k=[1 1 1; 1 1 1; 1 1 1];
length = (s* elements) - (elements-1);
K = zeros(length,length);
for j = 0:elements-1
index =(1:s);
n = index + j*(s-1);
K(n,n) = k(1:s,1:s);
end
for i = 1:elements-1
K(((i*s)-(i-1)), ((i*s)-(i-1))) = k(1,1)+k(s,s);
end
K
This does exactly what I want I answered my own question nevermind. Here it is for reference.
Related Question