patternpythonMinor
Simplifying loop for Incidence Matrix
Viewed 0 times
loopincidenceforsimplifyingmatrix
Problem
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:
Can this be simplified?
b<-diag(-1,n2)
a<-b
for (i in 1:(n1-1)) {
a<-cbind(a,b)
}Can this be simplified?
Solution
I can't think of anything faster than:
The
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-n1n2.Code Snippets
a <- matrix(diag(-1, n2), nrow = n2, ncol = n1 * n2)Context
StackExchange Code Review Q#37175, answer score: 3
Revisions (0)
No revisions yet.