matrix flow: to the right instead of downwards?
I'm not sure what you call this, but the default 'flow' of matrices is downwards (as seen below)
matrix(1,7,5)*(1:7)
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
What if your intention is to multiply the vector to the right instead of downwards? Is there a better way to write the command below? Is there a toggle for column instead of row (same for replicate(7,1:7)
it assumes downwards flow (paste row vectors开发者_运维技巧 downwards instead of column vectors to the right); is transpose the solution?)
t(t(matrix(1,7,5))*(1:5))
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
If you really want to do this a lot after defining the matrix you can always make an operator yourself:
'%mat%'<- function(x,y)t(t(x)*y)
matrix(1,7,5)%mat%1:5
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 2 3 4 5
[3,] 1 2 3 4 5
[4,] 1 2 3 4 5
[5,] 1 2 3 4 5
[6,] 1 2 3 4 5
[7,] 1 2 3 4 5
But I think it easier to just transpose twice as you said in the question:
t(t(matrix(1,7,5))*1:5)
Or of course opt to transpose the matrix once in the beginning, do everything you need to do with it and then transpose it back.
As far as I know there is no way to change the default behaviour of *, nor would you probably want too,
A matrix is simply a vector with a dim attribute. The elements of the matrix are stored in the vector in column-major order and there is no way to change this. *
is an element-by-element operator that recycles its arguments as necessary. You can see the recycling rule at work via:
> x <- matrix(1,7,5)
> x*1:5
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 2 4
[2,] 2 4 1 3 5
[3,] 3 5 2 4 1
[4,] 4 1 3 5 2
[5,] 5 2 4 1 3
[6,] 1 3 5 2 4
[7,] 2 4 1 3 5
You can see the multiplication is taking place by column and the vector (1:5
) is being recycled to be the same length as the matrix. Rather than transposing, you could use the matrix
function to re-size your matrix by row.
> matrix(x*1:5,nrow(x),ncol(x),byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 2 3 4 5
[3,] 1 2 3 4 5
[4,] 1 2 3 4 5
[5,] 1 2 3 4 5
[6,] 1 2 3 4 5
[7,] 1 2 3 4 5
I'm not sure that's the most efficient solution, but it's the best I can think of at the moment and it's slightly faster than using t
twice.
Do you mean this?
> matrix(rep(1:7,5), nrow=7, ncol=5)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
[4,] 4 4 4 4 4
[5,] 5 5 5 5 5
[6,] 6 6 6 6 6
[7,] 7 7 7 7 7
> matrix(rep(1:7,5), nrow=5, ncol=7, byrow=TRUE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 2 3 4 5 6 7
[2,] 1 2 3 4 5 6 7
[3,] 1 2 3 4 5 6 7
[4,] 1 2 3 4 5 6 7
[5,] 1 2 3 4 5 6 7
精彩评论