[R] Equivalent to matlab ".*" operator in R
John C Frain
frainj at gmail.com
Wed Nov 19 22:48:13 CET 2014
What you have written does not work in Matlab -
>> y = [0 0;0.5 0.5;1 1]
y =
0 0
0.5000 0.5000
1.0000 1.0000
>> z = [12, -6]
z =
12 -6
.
>> y .* z
Error using .*
Matrix dimensions must agree.
When dimensions agree it you get the same result in R as in Matlab by using
the * operator
> y = matrix(cbind(c(0, 0.5, 1),c(0, 0.5, 1)),ncol=2)
> y
[,1] [,2]
[1,] 0.0 0.0
[2,] 0.5 0.5
[3,] 1.0 1.0
> z = matrix(1:6, ncol=2)
> z
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> prod <- matrix(y*z,2)
> prod
[,1] [,2] [,3]
[1,] 0 3 2.5
[2,] 1 0 6.0
> prod <- matrix(y*z)
> prod
[,1] [,2]
[1,] 0 0.0
[2,] 1 2.5
[3,] 3 6.0
>
John C Frain
3 Aranleigh Park
Rathfarnham
Dublin 14
Ireland
www.tcd.ie/Economics/staff/frainj/home.html
mailto:frainj at tcd.ie
mailto:frainj at gmail.com
On 19 November 2014 16:48, Boris Steipe <boris.steipe at utoronto.ca> wrote:
> Or ... if you mean "simpler" as in "less to type", you can define your own
> binary operator by enclosing it in "%" signs, and the assign any of the
> previously proposed solutions, e.g.
>
> y = matrix(cbind(c(0, 0.5, 1),c(0, 0.5, 1)),ncol=2)
> z = matrix(c(12, -6),ncol=2)
> '%.*%' <- function(a,b) {a * rep(b, each=3)}
>
>
> y %.*% z
>
>
> [,1] [,2]
> [1,] 0 0
> [2,] 6 -3
> [3,] 12 -6
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list