 # Operation on columns of a matrix

Hello there,

I would like to ask a question regarding an operation on two columns of a matrix as you can see below. Here I proposed two functions to perform the task. The function f1 has two allocations even though I used @view, while the function f2 has no allocation. I am wondering whether it is possible to perform the task with no allocations without using a loop as proposed in function f2? Thanks in advance!

``````f1(x,A,iA,iB) = x .= view(A,:,iA) - view(A,:,iB);
function f2(x,A,iA,iB)
@inbounds @simd for i in 1:size(A,1)
x[i] = A[i,iA] - A[i,iB]
end
end
A = rand(10_000,10_000);
x1 = rand(10_000);
x2 = rand(10_000);
x0 = A[:,6] -  A[:,8];
@time f1(x1,A,6,8);
@time f2(x2,A,6,8);
@test x0 ≈ x1
@test x0 ≈ x2
``````

The allocation is occurring on the right hand side of th assignment because you have `-` instead of `.-`

``````julia> f3(x,A,iA,iB) = x .= view(A,:,iA) .- view(A,:,iB);

julia> begin
x1 = rand(10_000);
x2 = rand(10_000);
x3 = rand(10_000);
x0 = A[:,6] -  A[:,8];
@btime f1(\$x1, \$A, 6, 8);
@btime f2(\$x2, \$A, 6, 8);
@btime f3(\$x3, \$A, 6, 8);
end
13.495 μs (2 allocations: 78.20 KiB)
4.723 μs (0 allocations: 0 bytes)
5.556 μs (0 allocations: 0 bytes)``````
2 Likes

I am wondering, why you want to achieve this?

The allocation is occurring on the right hand side of th assignment because you have `-` instead of `.-`

Indeed, you were right! I didn’t check it carefully. Thanks for your help!