[R] Looking for a cleaner way to implement a setting certainindices of a matrix to 1 function

Prasenjit Kapat kapatp at gmail.com
Thu May 10 00:26:28 CEST 2007


On Tuesday 08 May 2007 05:45:53 pm Leeds, Mark (IED) wrote:
> That's a good idea : I didn't realize that my matrices would look so bad
> in the final email. All I want
> To do is output 1's in the diagonal elements and zero's everywhere else
> but the matrix is not square so by diagonals I
> Really mean if
>
> Lagnum = 1 then the elements are (1,1), (2,2), (3,3),(4,4),(5,5),(6,6)
>
> Lagnum = 2 then the elements (1,1), (2,2),
> (3,3),(4,4),(5,5),(6,6),(7,1),(8,2),(9,3),(10,4),(11,5),(12,6)
>
> Lagnum = 3 then the elements (1,1), (2,2),
> (3,3),(4,4),(5,5),(6,6),(7,1),(8,2),(9,3),(10,4),(11,5),(12,6),(13,1),(1
> 4,2),(15,3),(16,4),(17,5),
> (18,6)
>
> And lagnum always has to be greater than or equal to 1 and less than or
> equal to (number of cols/number of rows ). Thanks
> For your advice.

I think, the kronecker product method (by Gabor) is a cleaner solution. 
Something like:

kronecker(matrix(1,1,Lagnum), diag(K)).

My experience with such constructions, in really large dimensions, is that: 
kronecker(...) is much faster than {r,c}binds and rep(...).

Regards
PK



More information about the R-help mailing list