f

#### how to extract diagonal from a matrix

```Hi,
I have a similar matrix to this:

1 0 0 0
0 3 0 0
0 0 2 0
0 0 0 5

what function in matlab would extract a vector like this:

1 3 2 5

?
```
 0
paulia71 (23)
6/14/2007 4:56:19 PM
comp.soft-sys.matlab 211266 articles. 22 followers. lunamoonmoon (257) is leader.

4 Replies
557 Views

Similar Articles

[PageSpeed] 44

```In article <ef5ac76.-1@webcrossing.raydaftYaTP>,
Paulina  <paulia7@hotmail.com> wrote:
>I have a similar matrix to this:

>     1 0 0 0
>     0 3 0 0
>     0 0 2 0
>     0 0 0 5

>what function in matlab would extract a vector like this:

>1 3 2 5

One way:

X(sub2ind(size(X),1:size(X,1),1:size(X,2)))

Another way:
X((1+1:size(X,1)).*(1:size(X:1))/2)
--
Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us.       -- Ecclesiastes
```
 0
roberson2 (8602)
6/14/2007 5:01:56 PM
```Walter Roberson wrote:
> In article <ef5ac76.-1@webcrossing.raydaftYaTP>,
> Paulina  <paulia7@hotmail.com> wrote:
>> I have a similar matrix to this:
>
>>     1 0 0 0
>>     0 3 0 0
>>     0 0 2 0
>>     0 0 0 5
>
>> what function in matlab would extract a vector like this:
>
>> 1 3 2 5
>
> One way:
>
> X(sub2ind(size(X),1:size(X,1),1:size(X,2)))
>
> Another way:
> X((1+1:size(X,1)).*(1:size(X:1))/2)

--
```
 0
none1568 (7453)
6/14/2007 5:04:13 PM
```In article <f4rsgl\$kgc\$1@aioe.org>, dpb  <none@non.net> wrote:
>Walter Roberson wrote:
>> In article <ef5ac76.-1@webcrossing.raydaftYaTP>,
>> Paulina  <paulia7@hotmail.com> wrote:
>>> I have a similar matrix to this:

>>>     1 0 0 0
>>>     0 3 0 0
>>>     0 0 2 0
>>>     0 0 0 5

>>> what function in matlab would extract a vector like this:

>>> 1 3 2 5

Yes, that would work as well, provided that x doesn't happen to be
a row or column vector: it it is, then diag(x) would do the opposite,
return a square matrix with those values on the diagonal.
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer
```
 0
roberson2 (8602)
6/14/2007 6:14:26 PM
```Walter Roberson wrote:
> In article <f4rsgl\$kgc\$1@aioe.org>, dpb  <none@non.net> wrote:
>> Walter Roberson wrote:
>>> In article <ef5ac76.-1@webcrossing.raydaftYaTP>,
>>> Paulina  <paulia7@hotmail.com> wrote:
>>>> I have a similar matrix to this:
>
>>>>     1 0 0 0
>>>>     0 3 0 0
>>>>     0 0 2 0
>>>>     0 0 0 5
>
>>>> what function in matlab would extract a vector like this:
>
>>>> 1 3 2 5
>
>
> Yes, that would work as well, provided that x doesn't happen to be
> a row or column vector: it it is, then diag(x) would do the opposite,
> return a square matrix with those values on the diagonal.

"I have a similar matrix to this:
1 0 0 0
0 3 0 0
0 0 2 0
0 0 0 5"

Looks like it would meet the criterion to me... :)

--

```
 0
none1568 (7453)
6/14/2007 10:30:46 PM