I have a 30 x 30 matrix in R and I want the values to be multiplied of their column and row number. For example the first value is [1] * [1] = 1
mat2 <- matrix(nrow= 30, ncol = 30)
We can use row and col to get the index of row/columns and use that to multiply
mat2 <- row(mat2) *col(mat2)
If you know the size of the matrix, you can also use outer() and construct the matrix directly in one step.
mat2 <- outer(seq(30), seq(30))
# other simple variations:
outer(1:30, 1:30)
seq(30) %o% seq(30)
1:30 %o% 1:30
Related
I want to generate an nxm matrix. Suppose its 100x3. I want each row to sum to 1 (so two "0"'s and one "1").
sample(c(0,0,1),3)
will give me 1 row but is there a very fast way to generate the whole matrix without an rbind?
Thank you!
No loops, no transposition. Just create a matrix of zeros and replace one entry per row with 1 by sampling the rows.
m <- matrix(0, 100, 3)
nr <- nrow(m)
m[cbind(1:nr, sample(ncol(m), nr, TRUE))] <- 1
all(rowSums(m) == 1)
# [1] TRUE
mat <- matrix(runif(300),ncol=3)
mat[] <- as.numeric(t(apply(mat, 1, function(r) r == max(r))))
t(apply(t(matrix(rep(c(0,0,1),300),nrow = 3)), 1, function(x) sample(x)))
Since you want single 1 for a row, the problem can be restated to select a column entry randomly that has 1 for each row.
So you can do like,
m <- 3; n<-100
rand_v <- floor(runif(n)*3)+1
mat <- matrix(0,n,m)
idx <- cbind(1:n,rand_v)
mat[idx] <- 1
Hope this helps.
If I have multiple matrices like
mymat <- matrix(c(1,2,3,8,6,1,1,3,1) , nrow=3, ncol=3)
matrix_list <- replicate(2, mymat)
column_sums <- colSums(matrix_list)
This shows me that row two has the highest sum, but how would I create a code that tells me that row two has the highest sum in both matrices? So it will just show me a vector of 2,2. I tried this
for(i in 1:2) {
S <- max(matrix_list[i, ])
}
However this is not doing the job. Any help would be appreciated.
apply(column_sums, 2, which.max)
#[1] 2 2
We can use max.col
max.col(t(column_sums), "first")
#[1] 2 2
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.
I want to get the column means for the last list element, which is a sparse matrix multiplied times a regular matrix. Whenever I use colMeans, however, I get an error. For example:
# Use the igraph package to create a sparse matrix
library(igraph)
my.lattice <- get.adjacency(graph.lattice(length = 5, dim = 2))
# Create a conformable matrix of TRUE and FALSE values
start <- matrix(sample(c(TRUE, FALSE), 50, replace = T), ncol = 2)
# Multiply the matrix times the vector, and save the results to a list
out <- list()
out[[1]] <- my.lattice %*% start
out[[2]] <- my.lattice %*% out[[1]]
# Try to get column means of the last element
colMeans(tail(out, 1)[[1]]) # Selecting first element because tail creates a list
# Error in colMeans(tail(out, 1)[[1]]) :
# 'x' must be an array of at least two dimensions
# But tail(out, 1)[[1]] seems to have two dimensions
dim(tail(out, 1)[[1]])
# [1] 25 2
Any idea what's causing this error, or what I can do about it?
It looks like explicitly calling the colMeans function from the Matrix package works:
> Matrix::colMeans(tail(out, 1)[[1]])
# [1] 4.48 5.48
Thanks to user20650 for this suggestion.
I have a row vector and a column vector say c(1,2), c(7,100). I want to extract (1,7), (2,100).
Out, I find Matrix[row, column] will return a cross-product thing not just a vector of two numbers.
What should I do?
You want to exploit the feature that if m is a matrix containing the row/col indices required, then subsetting by passing m as argument i of [ gives the desired behaviour. From ?'['
i, j, ...: indices specifying elements to extract or replace.
.... snipped ....
When indexing arrays by ‘[’ a single argument ‘i’ can be a
matrix with as many columns as there are dimensions of ‘x’;
the result is then a vector with elements corresponding to
the sets of indices in each row of ‘i’.
Here is an example
rv <- 1:2
cv <- 3:4
mat <- matrix(1:25, ncol = 5)
mat[cbind(rv, cv)]
R> cbind(rv, cv)
rv cv
[1,] 1 3
[2,] 2 4
R> mat[cbind(rv, cv)]
[1] 11 17
You can use 2 column subsetting matrices inside [:
mx <- matrix(1:200, nrow=2)
mx[cbind(c(1, 2), c(7, 100))]
produces:
[1] 13 200