MATLAB: Change an element in diagonal of matrix

diagdiagonalelement

As example
A=magic(5);
result=diag(A,-1);
How can I change an element of this diagonal array when I don't know their indices?

Best Answer

I understand that you want to update the elements stored at a specified diagonal without knowing the element indices.
One way to do this could be to create a new matrix of ones along the specified diagonal with rest of the elements set to 0. This matrix then can be used as a reference to update the elements in original matrix. Try the following code snippet to increment the elements at the specified diagonal by 2:
% out: updated matrix, n: size of the input matrix, shift: diagonal selection
function out = update_diagonal(n,shift)
A=magic(n)
result=diag(A,shift);
% Create matrix of ones along specified diagonal
iden = diag(ones(n-abs(shift),1),shift);
% Modify the elements at location of ones in 'iden'. Here, increment all elements
% along the specified diagonal by 2
A(iden(:,:)~=0) = A(iden(:,:)~=0)+2;
out = A;
I hope this answers your question.