Julia中定义行合并rbind和列合并函数cbind----对比R语言

cbind和rbind

这两个函数, 是合并矩阵或者数据框时可以使用, 只是机械的合并, 但是julia中没有找到解决方案.

R中示例

代码

a = matrix(1:9,3,3)
a
b = matrix(10:18,3,3)
b
cbind(a,b)
rbind(a,b)

结果

> a = matrix(1:9,3,3)
> a
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> b = matrix(10:18,3,3)
> b
     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18
> cbind(a,b)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    4    7   10   13   16
[2,]    2    5    8   11   14   17
[3,]    3    6    9   12   15   18
> rbind(a,b)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[4,]   10   13   16
[5,]   11   14   17
[6,]   12   15   18

Julia语言

Julia中只有行合并类似的函数: vcat
如果需要列合并, 可以对其转置.
如:
a和b
行合并:

vcat(a,b)

列合并:

vcat(a',b')'

这里定义两个函数, 使用更方便: rbind和cbind

function cbind(A,B)
    X = vcat(A',B')'
    return(X)
end

function rbind(A,B)
    X = vcat(A,B)
    return(X)
end
## test
a = reshape(collect(1:9),3,3)
b = reshape(collect(10:18),3,3)
rbind(a,b)
cbind(a,b)

结果:

Main> rbind(a,b)
6×3 Array{Int64,2}:
  1   4   7
  2   5   8
  3   6   9
 10  13  16
 11  14  17
 12  15  18

Main> cbind(a,b)
3×6 Array{Int64,2}:
 1  4  7  10  13  16
 2  5  8  11  14  17
 3  6  9  12  15  18

使用vcat函数操作

Main> vcat(a,b)
6×3 Array{Int64,2}:
  1   4   7
  2   5   8
  3   6   9
 10  13  16
 11  14  17
 12  15  18

Main> vcat(a',b')'
3×6 Array{Int64,2}:
 1  4  7  10  13  16
 2  5  8  11  14  17
 3  6  9  12  15  18

搞定!!!

猜你喜欢

转载自blog.csdn.net/yijiaobani/article/details/82789835