I am rewriting this code below using broadcasting to improve performance and clarity.
var = zeros(Float64, 9, 109, 50)
data = rand(9*109*50)
for j in 1:9
# Extract the slice of data corresponding to the current `j`
temp = data[((j-1)*109*50) + 1 : (j*109*50)]
# Reshape the slice and directly assign it to `var`
var[j, :, :] .= reshape(temp, 109, 50)
end
This code below gives error.
var = zeros(Float64, 9, 109, 50)
data = rand(9*109*50)
@. var = reshape(data, 9, 109, 50)
ERROR: DimensionMismatch: array could not be broadcast to match destination
Stacktrace:
[1] check_broadcast_shape
@ ./broadcast.jl:547 [inlined]
[2] check_broadcast_axes
@ ./broadcast.jl:550 [inlined]
[3] check_broadcast_axes
@ ./broadcast.jl:553 [inlined]
[4] instantiate
@ ./broadcast.jl:305 [inlined]
[5] materialize!
@ ./broadcast.jl:878 [inlined]
[6] materialize!(dest::Array{…}, bc::Base.Broadcast.Broadcasted{…})
@ Base.Broadcast ./broadcast.jl:875
[7] top-level scope
@ REPL[10]:1
Some type information was truncated. Useshow(err)
to see complete types.
while following code below works fine but i see increase in memory allocation. Why above code gives error?
var = zeros(Float64, 9, 109, 50)
data = rand(9*109*50)
var .= reshape(data, 9, 109, 50)