Why am I getting the error: "Error using + Matrix dimensions must agree."?
Mostrar comentarios más antiguos
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 comentarios
The MATLAB approach using TOEPLITZ:
N = 21;
M = toeplitz([2,-1,zeros(1,N-2)]);
M([1,end]) = 1
Steven Lord
el 22 de Feb. de 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.
Respuesta aceptada
Más respuestas (1)
KSSV
el 29 de Sept. de 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 comentario
KSSV
el 29 de Sept. de 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.
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!