Getting rid of allocations when copying data from one row to another

I’m writing model code that requires me to replace the border values with the opposite domain values (our domain is everything but the border of the matrix) and since we have to run this value swap every iteration, I was wondering if there is a way I can not end up with array copies occurring in my code.

@views @inbounds function boundary_condition!(arr)
  arr[begin, begin] = arr[end-1, end-1]
  arr[end, end] = arr[begin+1, begin+1]
  arr[begin, end] = arr[end-1, begin+1]
  arr[end, begin] = arr[begin+1, end-1]

  arr[begin, begin+1:end-1] = arr[end-1, begin+1:end-1]
  arr[end, begin+1:end-1] = arr[begin+1, begin+1:end-1]
  arr[begin+1:end-1, begin] = arr[begin+1:end-1, end-1]
  arr[begin+1:end-1, end] = arr[begin+1:end-1, begin+1]

Is there a better/more effcient way to do this?

Maybe @. when copying slices ?

1 Like

Also, functions return their last statement - here a view of the matrix which must be allocated. I suggest a return nothing at the end to avoid this.

ETA: I realise since you’re @inlineing it the compiler is probably not allocating the return value anyway.


This did the trick!

1 Like