Question

Can someone explain what's going on here?

octave:1> t = eye(3)
t =

Diagonal Matrix

   1   0   0
   0   1   0
   0   0   1

octave:2> diag(t(3,:))
ans =

Diagonal Matrix

   0   0   0
   0   0   0
   0   0   1

octave:3> diag(t(2,:))
ans =

Diagonal Matrix

   0   0   0
   0   1   0
   0   0   0

octave:4> diag(t(1,:))
ans =  1

Why do the first two give back 3x3 matrices but the last one is just a number?

Was it helpful?

Solution

The problem arises because of the way t(1,:) was created, from eye(3).

If you output the rows of t individually the results are:

octave.28> t(1,:)
ans = 

**Diagonal Matrix**

   1   0   0

octave.29> t(2,:)

ans = 

   0   1   0

octave.30> t(3,:)

ans = 

   0   0   1

For some reason (I can't explain) t(1,:) is still recognized as a diagonal matrix, while t(2,:) and t(3,:) are vectors. When you call diag(t(:,1)) it is not receiving a vector argument, but rather a matrix. If you convert t(:,1) to vector before evaluation you get the expected result.

octave.31> diag(vec(t(1,:)))
ans = 

**Diagonal Matrix**

   1   0   0
   0   0   0
   0   0   0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top