Why am I getting the error: "Error using + Matrix dimensions must agree."?
Show older comments
Hello,
I am trying to create a 21x21 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 2x2 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.
2 Comments
The MATLAB approach using TOEPLITZ:
N = 21;
M = toeplitz([2,-1,zeros(1,N-2)]);
M([1,end]) = 1
Steven Lord
on 22 Feb 2023
Another approach is to use the technique shown in the "Create Tridiagonal Matrix" example on the spdiags documentation page and adjust the first and last elements.
Accepted Answer
More Answers (1)
KSSV
on 29 Sep 2016
This line:
K(i:j,i:j) = K(i:j,i:j) + k1 ;
when i = 1 and j = 3 ;K becomes 3X3..i.e. K(1:3,1:3) and to this 3x3 matrix you are adding 2x2 matrix. How you expect them to get added? So the error matrix dimensions do not agree. So your code runs for i = 1, and j = 1,2 and after this throws error.
1 Comment
KSSV
on 29 Sep 2016
I guess this is FEM related. To make global stiffness matrix, you shall have nodal connectivity matrix. You must extract the matrix based on nodal connectivity.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!