I want to multiply several matrices (all of same dimensions) to a vector beta. I have tried two versions, to store the matrices, either as a vector of matrices, or as a tri-dimensions array.
Is it normal that the version with the vector of matrices runs faster?
using BenchmarkTools
nid =10000
npar = 5
x1 = reshape(repeat([1], nid * npar), nid,:)
x2 = reshape(repeat([2], nid * npar), nid,:)
x3 = reshape(repeat([3], nid * npar), nid,:)
X = reshape([x1 x2 x3], nid, npar, :);
X1 = [x1, x2, x3]
beta = rand(npar)
function f(X::Array{Int,3}, beta::Vector{Float64})::Array{Float64}
hcat([ X[:,:,i] * beta for i=1:size(X,3)]...)
end
function g(X::Array{Array{Int,2},1}, beta::Vector{Float64})::Array{Float64}
hcat([X[i] * beta for i=1:size(X)[1]]...)
end
f(X,beta);
g(X1,beta);
@benchmark f(X, beta)
@benchmark g(X1, beta)
Results indicate that f takes almost 2x time of g. Is it a normal pattern, or I am not using the 3D Array properly?