Feature request: easy R-like construction of diagonal and identity matrices

2,838 views
Skip to first unread message

dje

unread,
Jun 25, 2015, 1:25:17 PM6/25/15
to stan-...@googlegroups.com
Hi,

I've got what's perhaps an very minor feature request, but I would find it convenient. In R, one can create a diagonal n by n matrix from an n-length vector x via diag(x). The output has the elements of x on the diagonal, and 0 on the off-diagonal elements.

Likewise, one can make an identity n by n matrix by supplying an integer n, so diag(n) is the identity matrix of dimension n by n.

Currently, I implement these by initializing a matrix and then writing loops over them and assigning values as needed. It's not at all hard to do, but it's slightly inconvenient.

Thanks for your time.

David

dje

unread,
Jun 25, 2015, 1:37:34 PM6/25/15
to stan-...@googlegroups.com
I have discovered that this already exists. My mistake.

Daniel Lee

unread,
Jun 25, 2015, 1:41:59 PM6/25/15
to stan-...@googlegroups.com

What did you use?

I think this works:
diag_matrix(rep_vector(1.0, n))

--
You received this message because you are subscribed to the Google Groups "Stan users mailing list" group.
To unsubscribe from this group and stop receiving emails from it, send an email to stan-users+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Bob Carpenter

unread,
Jun 25, 2015, 11:58:44 PM6/25/15
to stan-...@googlegroups.com
You almost never want to be explicitly building up
a diagonal matrix. May I ask what do you do with it once it's
constructed?

We have some diagonal multiplication routines such as

diag_pre_multiply(a, b) = diag(a) * b

that are much more efficient for diagonal matrices.

And you don't want to be calling multi_normal unless absolutely
necessary --- it should never be called with a diagonal covariance
matrix. That is, instead of

y ~ multi_normal(mu, diag(a))

you just want to use the vectorized univariate form to get the
same result:

y ~ normal(mu, a);

- Bob

dje

unread,
Jun 26, 2015, 10:43:43 AM6/26/15
to stan-...@googlegroups.com
Bob, Dan:

Thanks for the tips. I'll get the hang of this one day. ;)

Bob Carpenter

unread,
Jun 26, 2015, 11:23:57 AM6/26/15
to stan-...@googlegroups.com
So will we. We imagine a world where we can do program
transforms eventually that'll do this all automatically. But
that's a long way off.

In the meantime, Stan's just like any other programming language,
where there are ways to write more efficient code, but it's a long
tail of computational and numerical analysis techniques (like
using log_sum_exp() or log1p() instead of coding them directly).

- Bob
Reply all
Reply to author
Forward
0 new messages