I have a 3 dimensional complex F64 array. I want to run the inv() over the inner two dimensions and broadcast along the outer dimension. When I try simple broadcasting inv.(A) I get different results than if I do a for-loop. How do I specify the dimension I want to broadcast over?

The easiest solution would be to have a Vector of Matrix objects. That said, it is very rare for inv to be the best method for solving problems. What’s the usecase?

Broadcast is completely point-wise. That is, it applies to every element in the array, not slices thereof. Thus if you want to use broadcast across slices like this, you need to use some sort of array-of-arrays structure.

The matrix represents the mapping of inputs to outputs of an electrical circuit. The outer dimension represents how that matrix changes at different frequency points. So to flip the mapping from outputs to inputs I just need to invert the matrix, but I want to do it at each frequency so I need to invert the matrix for each matrix along the array. It sounds like a 1D array of 2D arrays would be the best approach.

It looks like mapslices might be the method I was looking for. But, perhaps there is a better way to do what I want than iterating over the outer dimension?

I found this thread because I had the same question, essentialy. I was not satisfied with the answers because I wanted

a view

high performance

So I created a typestable, zero allocation (so it is fast) method for selectdim. Like selectdim it returns a view. Unlike Julia’s version, its second argument must be a Val.

@generated function Base.selectdim(a,::Val{d},i) where{d}
precols = ()
pstcols = ()
for i = 1:d-1
precols = (precols...,:)
end
for i = 1:ndims(a)-d
pstcols = (pstcols...,:)
end
return quote
return view(a,$(precols...),i,$(pstcols...))
end
end
a = randn(2,4,5)
g = selectdim(a,Val(3),2) # view to a[:,:,2]