3
\$\begingroup\$

I had to work in the Transport Problem and we're asked to try to make the fastest code for big matrices, so we're advised to try to avoid loops. And the only one I've got and I cannot imagine how to simplify it is this one for making an incidence matrix (with 1s, 0s and -1s) like that:

b<-diag(-1,n2)
a<-b
for (i in 1:(n1-1)) {
 a<-cbind(a,b)
}

Can this be simplified?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 11, 2013 at 21:55
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I can't think of anything faster than:

a <- matrix(diag(-1, n2), nrow = n2, ncol = n1 * n2)

The n2 * n2 values inside diag(-1L, n2) will be recycled n1 times to fill the final matrix of dimensions n2-by-n1*n2.

answered Dec 11, 2013 at 23:38
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.