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

雨燕双飞 提交于 2019-12-11 14:14:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!