# [petsc-users] Get and Set the k-th diagonal elements

Barry Smith bsmith at mcs.anl.gov
Fri May 6 21:08:55 CDT 2011

```   Are the diagonals constant values, or does each row have a separate value?

Barry

On May 6, 2011, at 4:23 PM, Xiangdong Liang wrote:

> Thanks for your response, Barry. I am going to solve A_n x = b for
> different A_n's. The difference between A_n's are only the main
> diagonal and the k-th diagonal. I  want to generate the matrix A once,
> and each time modify the main and k-th diagonals to get a new A_n.
> That's the reason I am asking for efficient way to get and set k-th
> diagonal. I may not need to get the k-th diagonal if I keep the adding
> difference between each n. However, I still need to set the k-th
> diagonal anyway.
>
> More precisely, suppose my N-by-N matrix A=[a1, a2; a3, a4], where a1,
> a2, a3 and a4 are n/2-by-n/2 sub-matrix. I am trying to modify the
> diagonals of a1, a2, a3 and a4, which is the main and n/2-th diagonal
> of A.
>
> Thanks.
>
> Xiangdong
>
>
>
> On Fri, May 6, 2011 at 5:04 PM, Barry Smith <bsmith at mcs.anl.gov> wrote:
>>
>>  How are you planning to use these diagonals? This might help us make suggestions as to what is a reasonable approach. Accessing diagonals is not a natural operation for sparse matrices stored by rows or columns.
>>
>>   Barry
>>
>>
>>
>> On May 6, 2011, at 3:56 PM, Xiangdong Liang wrote:
>>
>>> Hello everyone,
>>>
>>> I am wondering whether there is some function like MatGetDiagonal to
>>> get the k-th diagonal (above or below the main diagonal) of the matrix
>>> A. If I have to write my own function, what built-in function should I
>>> use to get a particular element of A? It seems that MatGetValues
>>> returns a block of matrix. I guess if I only extract one element once,
>>> it would not be efficient. Any suggestions? Thanks.
>>>
>>> Best,
>>> Xiangdong
>>
>>

```