简体   繁体   中英

adding a small value to only the diagonal elements of a matrix

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM