Wondering how to duplicate a vector into a matrix in R. For example
v = 1:10
dup = duplicate(V,2)
where dup looks like rbind(1:10,1:10). Thanks
I think you're looking for replicate.
t(replicate(2, v))
Alternatively:
matrix(v, nrow=2, ncol=length(v), byrow=TRUE)
Personally I just multiply it by a ones vector ..
for instance, if v is a column vector :
v [1 1] -> [v v]
Similar to Moud's answer but with some more clarity.
n <- 10
v <- c(1,4,3,6,4,7,8,1) # random
t(t(rep(1, n))) %*% v
Should be fast but not as elegant as some of the other answers.
Related
Functional way to stack list of 2d matrices into 3d matrix
↑ From this Q I learned I could use simplify2array for this task.
However, it doesn't solve my problem. Unfortunately, I simply don't know how to describe the issue without showing it on an example…
l = list()
l[[1]] = matrix(1:110, nrow=10)
l[[2]] = matrix(110:1, nrow=10)
l = simplify2array(l)
dim(l)
This prints:
10 11 2
Problem is, I would like the dimensions to be set in a different manner. I would like dim(l) to print instead:
2 11 10
How to achieve this?
Use aperm as a generalized transpose (where a is as in the Note at the end).
aa <- aperm(a, 3:1)
dim(aa)
## [1] 2 11 10
Note
We assume that the input a is:
l = list()
l[[1]] = matrix(1:110, nrow=10)
l[[2]] = matrix(110:1, nrow=10)
a <- simplify2array(l)
In pytorch. I want to multiply each vector of Matrix A by each vector of Matrix B:
A = M x N
B = L x N
result = (M x L) x N
Try:
result = A[:, None, :] * B[None, ...]
I tried this, and it is working:
torch.einsum('bj,aj->baj', input_unfolded, self.weights)
You can design any multiplication pattern using this approach.
My question is simple but still I haven't been able to find the solution online.
I have a vector, e.g. a = c(7,3,5). I need to convert it to b = c(0,1,2,3,4,5,6,0,1,2,0,1,2,3,4). I can do that with a loop, but its notoriously slow when length(a) > 500000.
m <- 0
n <- 0
for (i in 1:length(a)) {
m <- n+1;
n <- n+a[i];
b[m:n] <- (0:(a[i]-1));
}
Is there a one-liner in R that can produce the described behaviour really fast? Can that same approach convert vector a into c = c(0,0,0,0,0,0,1,0,0,1,0,0,0,0,1)?
Several options in the comments, but not one posted in the answer area, so while the hunt for a possible duplicate is on, here's a consolidation of what we have so far. The most direct/logical alternative for each option is listed first.
## To get your first vector
sequence(a) - 1 # #Henrik
ave(1:sum(a), rep(seq_along(a), a), FUN = seq_along) - 1 # #akrun
## To get your second vector
tabulate(cumsum(a)) # #alexis_laz
{ x <- integer(sum(a)) ; x[cumsum(a)] <- 1; x } # #DavidArenburg
{ x <- sequence(a) - 1 ; as.integer(c(diff(x) != 1, TRUE)) } # #Henrik
sequence(a) %/% rep(a, a) # #GL_Li
This answer is Community Wikied, so feel free to edit and add alternatives.
I have a (13*122) x (14) matrix (122 stacked 13x14's), which I made into a list of 122 individual 13 x 14 matrices.
set.seed(1)
mat = matrix(rnorm(13*122*14,0,1),(13*122),14)
I have another matrix that is 122 x 14.
beta = matrix(rnorm(122*14,0,1),122,14)
I want to multiply each stacked matrix by the correspond row in beta, so the first 13 x 14 matrix would get multiplied by beta[1,] (which is 14x1), so I'd get 13x1 matrix, etc.
Should I do this with a list or is it unnecessary? I would like it to be as fast as possible.
I want to return a 13 x 122 matrix.
We could split the matrix into a 'list' of length '122' and use mapply to do the %*% of corresponding elements of 'lst' and rows of 'beta'
lst <- lapply(split(1:nrow(mat),(1:nrow(mat)-1) %/%13+1),
function(i) mat[i,])
res <- mapply(`%*%`, lst, split(beta, row(beta)))
dim(res)
#[1] 13 122
Or we could convert the matrix to array and then do the multiplication, which I guess would be fast
mat1 <- mat #if we need a copy of the original matrix
dim(mat1) <- c(13, 122, 14)
mat2 <- aperm(mat1, c(1,3,2))
res2 <- matrix(, ncol=122, nrow=13)
for(i in 1:(dim(mat2)[3])){
res2[,i] <- mat2[,,i] %*%beta[i,]
}
all.equal(res, res2, check.attributes=FALSE)
#[1] TRUE
Try this:
mat <- lapply(1:122, function(x) matrix(data = rnorm(13*14,0,1), nrow = 13, ncol = 14))
mat2 <- lapply(1:122, function(x) mat[[x]] %*% beta[x,])
look for the book introduction to algorithms and look at page 331. There is a pseodu algortihm to do so. you have to make a three of matrix products where it will sort it so that it will be an optimum for multiplication but short hand, if you have three matrices M1 of m x n, M2 of n x v, M3 of v x w then you wish to know if (M1 * M2) * M3 or M1 * (M2 * M3) is better the answer is to calculate the to numbers mnv and nvw and deside which is biggest. the smallest one is always better.
Let's say you have a matrix
m <- matrix(1:25*2, nrow = 5, ncol=5)
How do you go from matrix subscripts (row index, column index) to a linear index you can use on the matrix. For example you can extract values of the matrix with either of these two methods
m[2,3] == 24
m[12] == 24
How do you go from (2,3) => 12 or 12 => (2,3) in R
In Matlab the functions you would use for converting matrix subscripts to linear indices and vice versa are ind2sub and `sub2ind
Is there an equivalent way in R?
This is not something I've used before, but according to this handy dandy Matlab to R cheat sheet, you might try something like this, where m is the number of rows in the matrix, r and c are row and column numbers respectively, and ind the linear index:
MATLAB:
[r,c] = ind2sub(size(A), ind)
R:
r = ((ind-1) %% m) + 1
c = floor((ind-1) / m) + 1
MATLAB:
ind = sub2ind(size(A), r, c)
R:
ind = (c-1)*m + r
For higher dimension arrays, there is the arrayInd function.
> abc <- array(dim=c(10,5,5))
> arrayInd(12,dim(abc))
dim1 dim2 dim3
[1,] 2 2 1
You mostly don't need those functions in R. In Matlab you need those because you can't do e.g.
A(i, j) = x
where i,j,x are three vectors of row and column indices and x contains the corresponding values. (see also this question)
In R you can simply:
A[ cbind(i, j) ] <- x
There are row and col functions that return those indices in matrix form. So it should be as simple as indexing the return from those two functions:
M<- matrix(1:6, 2)
row(M)[5]
#[1] 1
col(M)[5]
#[1] 3
rc.ind <- function(M, ind) c(row(M)[ind], col(M)[ind] )
rc.ind(M,5)
[1] 1 3
Late answer but there's an actual function for ind2sub in the base package called arrayInd
m <- matrix(1:25, nrow = 5, ncol=5)
# linear indices in R increase row number first, then column
arrayInd(5, dim(m))
arrayInd(6, dim(m))
# so, for any arbitrary row/column
numCol <- 3
numRow <- 4
arrayInd(numRow + ((numCol-1) * nrow(m)), dim(m))
# find the row/column of the maximum element in m
arrayInd(which.max(m), dim(m))
# actually which has an arr.ind parameter for returning array indexes
which(m==which.max(m), arr.ind = T)
For sub2ind, JD Long's answer seems to be the best
Something like this works for arbitrary dimensions-
ind2sub = function(sz,ind)
{
ind = as.matrix(ind,ncol=1);
sz = c(1,sz);
den = 1;
sub = c();
for(i in 2:length(sz)){
den = den * sz[i-1];
num = den * sz[i];
s = floor(((ind-1) %% num)/den) + 1;
sub = cbind(sub,s);
}
return(sub);
}