Change an element in diagonal of matrix

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?

댓글 수: 1

Kirby Fears
Kirby Fears 2015년 11월 25일
The size of diag(A,n) will always be (length(A)-abs(n)) by 1.
The indices of your diagonal array are 1 through 4. They correspond to elements (2,1), (3,2), (4,3), and (5,4) of A. This correspondence can be formulated just in terms of n and the size of A.
Does this help? I'm not sure what information you are seeking.

댓글을 달려면 로그인하십시오.

 채택된 답변

Tushar Athawale
Tushar Athawale 2015년 11월 25일

0 개 추천

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.

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2015년 11월 25일

0 개 추천

e.g.:
A=magic(5);
ii = diag(true(4,1),-1);
A(ii) = 100;
Sean de Wolski
Sean de Wolski 2015년 11월 25일
편집: Sean de Wolski 2015년 11월 25일

0 개 추천

The -1st diagonal is 2:n+1:end. You can index into that directly without ever needing diag/tril
n = 5;
x = magic(n);
didx = 2:n+1:numel(x);
% Change third element on -1st diagonal
x(didx(3)) = -100
x =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 -100 21 3
11 18 25 2 9

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

질문:

mat
2015년 11월 19일

답변:

2015년 11월 25일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by