问题
I am a newbie to matlab and I am trying to find out the inverse of matrix with very small values. When i try to find the inverse I get an error saying that the matrix is singular. One of the solutions suggested is to try and add some elements to the diagonal elements. I know i have to use eye and diag methods but I am not able come up the correct soltion.
Any comments will be helpful.
回答1:
If you just want to add the identity matrix or a multiple of it to your square matrix, you can do
A_new = A_old + k*eye(size(A_old));
where A_old
is your matrix and k
is some multiplier. If you want to add a different values to each diagonal element, you can do something like
A_new = A_old + diag(values);
where values
is a vector with as many number of elements as the number of columns (or rows) of your matrix A_old
.
If your matrix is large, it will be more memory efficient to use spdiags
as:
dim_A = size(A_old,1);
A_new = A_old + spdiags(values(:),0,dim_A,dim_A);
or use linear indexing like in Amro's answer.
回答2:
For a square matrix, you can add to the diagonal as:
[r,~] = size(M);
M(1:r+1:end) = M(1:r+1:end) + values;
where values
can be scalar or a vector of r
elements
来源:https://stackoverflow.com/questions/8016443/adding-a-small-value-to-only-the-diagonal-elements-of-a-matrix