Home > Net >  R equivalent of matrix in Python
R equivalent of matrix in Python

Time:09-30

I have following script in Python:

import numpy as np
a = range(2)
b = 14
out = np.mat([[k**i for i in a] for k in range(-b, b 1)])

What will be R equivalent of above python code?

CodePudding user response:

You can use the code below

a <- 2
b <- 14

MAT <- list()
for (i in 0:(a-1)){
  h = (-b:b)^i
  MAT[[i 1]] = h
 
}
out <- matrix(unlist(MAT), ncol = length(1:a), byrow = F)
print(out)
      [,1] [,2]
 [1,]    1  -14
 [2,]    1  -13
 [3,]    1  -12
 [4,]    1  -11
 [5,]    1  -10
 [6,]    1   -9
 [7,]    1   -8
 [8,]    1   -7
 [9,]    1   -6
[10,]    1   -5
[11,]    1   -4
[12,]    1   -3
[13,]    1   -2
[14,]    1   -1
[15,]    1    0
[16,]    1    1
[17,]    1    2
[18,]    1    3
[19,]    1    4
[20,]    1    5
[21,]    1    6
[22,]    1    7
[23,]    1    8
[24,]    1    9
[25,]    1   10
[26,]    1   11
[27,]    1   12
[28,]    1   13
[29,]    1   14

CodePudding user response:

let

a = 0:(m-1) #=range(m)
b = n

for any positive integer m and n

func <- function(m,n){
  x <- rep(1, 2*n   1)
  for (i in 1:(m-1)){
    y <- x * c(-n:n) ^ i
    x <- cbind(x,y)
  }
  x
}

this will do the same with your code

> func(2,14)
      x   y
 [1,] 1 -14
 [2,] 1 -13
 [3,] 1 -12
 [4,] 1 -11
 [5,] 1 -10
 [6,] 1  -9
 [7,] 1  -8
 [8,] 1  -7
 [9,] 1  -6
[10,] 1  -5
[11,] 1  -4
[12,] 1  -3
[13,] 1  -2
[14,] 1  -1
[15,] 1   0
[16,] 1   1
[17,] 1   2
[18,] 1   3
[19,] 1   4
[20,] 1   5
[21,] 1   6
[22,] 1   7
[23,] 1   8
[24,] 1   9
[25,] 1  10
[26,] 1  11
[27,] 1  12
[28,] 1  13
[29,] 1  14

CodePudding user response:

sapply will do this automatically for you. It is the idiomatic R solution, and it is most similar to the Python list comprehension.

b_range <- -14 : 14
c_range <- 0 : 1

out <- t(sapply(b_range, function(i) i * c_range, simplify = TRUE))
      [,1] [,2]
 [1,]    0  -14
 [2,]    0  -13
 [3,]    0  -12
 [4,]    0  -11
 [5,]    0  -10
 [6,]    0   -9
 [7,]    0   -8
 [8,]    0   -7
 [9,]    0   -6
[10,]    0   -5
[11,]    0   -4
[12,]    0   -3
[13,]    0   -2
[14,]    0   -1
[15,]    0    0
[16,]    0    1
[17,]    0    2
[18,]    0    3
[19,]    0    4
[20,]    0    5
[21,]    0    6
[22,]    0    7
[23,]    0    8
[24,]    0    9
[25,]    0   10
[26,]    0   11
[27,]    0   12
[28,]    0   13
[29,]    0   14

CodePudding user response:

Here is an approach using vectorization:

m <- 2
a <- 0:(m-1)
b <- 14
vals <- -b:b
matrix(vals^(rep(0:(m-1), each=length(vals))), ncol=2)
  • Related