如果可能,最好从一开始就创建具有所需列数的数组。这样,您只需填写这些列值。使用像hcat() 这样的过程的解决方案效率低下,因为它们每次都需要重新创建数组。
如果您确实需要将列添加到已经存在的数组中,最好一次性添加所有列,而不是使用hcat() 循环添加。例如。如果你开始:
n = 10; m = 5;
A = rand(n,m);
然后
A = [A rand(n, 3)]
将比:
for idx = 1:3
A = hcat(A, rand(n))
end
例如比较这两者在速度和内存分配上的差异:
n = 10^5; m = 10;
A = rand(n,m);
n_newcol = 10;
function t1(A::Array, n_newcol)
n = size(A,1)
for idx = 1:n_newcol
A = hcat(A, zeros(n))
end
return A
end
function t2(A::Array, n_newcol)
n = size(A,1)
[A zeros(n, n_newcol)]
end
# Stats after running each function once to compile
@time r1 = t1(A, n_newcol); ## 0.145138 seconds (124 allocations: 125.888 MB, 70.58% gc time)
@time r2 = t2(A, n_newcol); ## 0.011566 seconds (9 allocations: 22.889 MB, 39.08% gc time)