Bazman
Bazman

Reputation: 2150

Using diag() in R

I am looking at this piece of code which I am translating to Matlab, I only have the source code not a running version in R.

Result[,1:2]<-diag(max)

Where max is a [2*1] array.

I had assumed that this was creating a diagonal matrix on the rhs which is assigned to the first 4 elements in Result.

However, I now think that only the diagonal elements on the lhs should be changes (to the max values from the RHS). Is this the correct reading of the code?

Upvotes: 0

Views: 637

Answers (1)

agstudy
agstudy

Reputation: 121598

This code will not assign. Just compare matrix , elements by elements. It works only if you have the correct dimensions. Here an example:

set.seed(1234)

Result <- matrix(rnorm(20),nrow=2)
Result[,1:2] <= diag(max(c(2,2)))

     [,1]  [,2]
[1,]  TRUE FALSE
[2,] FALSE  TRUE

Here an example where you get error( the most probable case)

Result[,1:2] <= diag(max(c(2,4)))
Error in Result[, 1:2] <= diag(max(c(2, 4))) : non-conformable arrays

EDIT after OP edit

If the original code is

Result[,1:2] <- diag(max(c(2,2)))

   [,1] [,2]      [,3]       [,4]       [,5]
[1,]    1    0 0.4291247 -0.5747400 -0.5644520
[2,]    0    1 0.5060559 -0.5466319 -0.8900378

The code will assign a diagonal matrix (4th elemntss) as shwon a bove, but this will not work if you don't have the right dimension. Fo example:

  Result <- matrix(rnorm(6),nrow=3)
  Result[,1:2] <- diag(max(c(2,2)))

 Error in Result[, 1:2] <- diag(max(c(2, 2))) : 
 number of items to replace is not a multiple of replacement length

You have an error because results have more rows than RHS.

Result
           [,1]       [,2]
[1,] -1.2070657 -2.3456977
[2,]  0.2774292  0.4291247
[3,]  1.0844412  0.5060559

and RHS is

diag(max(c(2,2)))
     [,1] [,2]
[1,]    1    0
[2,]    0    1

Upvotes: 1

Related Questions