# 数组拼接问题求教

#1

2 3 4 3 4 5 4 5 6
5 6 7 6 7 8 7 8 9
8 9 10 9 10 11 10 11 12
#--------------------------------------------
a = Array{Float64, 2}[]
b = [1 2 3; 4 5 6; 7 8 9]
for i = 1:3
global b .+= 1
push!(a,b)
end
a
#--------------------------------------------

#2
``````julia> b = [1 2 3; 4 5 6; 7 8 9];

julia> a = similar(b, size(b, 1), 3size(b, 2));

julia> for i in 1:3
a[:, 3(i-1)+1:3i] .= b .+ i
end

julia> a
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12
``````

#3

#4

one-line-fighter: `mapreduce(x->b.+x, hcat, 1:3)`

``````julia> function foo(a)
a = similar(b, size(b, 1), 3size(b, 2));
for i in 1:3
a[:,3(i-1)+1:3i] .= b .+ i
end
a
end
foo (generic function with 3 methods)

julia> bar(b) = mapreduce(x->b.+x, hcat, 1:3)
bar (generic function with 1 method)

julia> @btime foo(\$b)
3.823 μs (28 allocations: 1.17 KiB)
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12

julia> @btime bar(\$b)
241.953 ns (8 allocations: 1.09 KiB)
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12
``````

#5

#6

#7

``````julia> function foo(b)
a = similar(b, size(b, 1), 3size(b, 2));
for i in 1:3
a[:,3(i-1)+1:3i] .= b .+ i
end
a
end
foo (generic function with 1 method)

julia> @btime foo(b)
108.884 ns (1 allocation: 336 bytes)
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12

julia> @btime bar(b)
471.353 ns (9 allocations: 1.13 KiB)
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12

julia> @btime foo(\$b)
101.058 ns (1 allocation: 336 bytes)
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12

julia> @btime bar(\$b)
287.423 ns (8 allocations: 1.09 KiB)
3×9 Array{Int64,2}:
2  3   4  3   4   5   4   5   6
5  6   7  6   7   8   7   8   9
8  9  10  9  10  11  10  11  12
``````

#8

#9

#10

@btime 会跑很多次求平均，\$ 是为了避免每次都重新初始化输入变量

#11

#12