Standard function name to skip intermediate step piping getindex call into vec

I am wondering about Julia conventions - is there a function or kwarg for skipping an intermediate type when taking an array through getindex and then vec?

More concretely, suppose we are doing a getindex call on a SparseMatrixCSC and convert the result into a vector:

using SparseArrays 
sa = sparse([1 0 1; 0 1 0]) 
x = vec(sa[1:2, 1:2]) 

What is returned by getindex is a SparseMatrixCSC:

typeof(sa[1:2, 1:2]) <: SparseMatrixCSC 

I want to skip the intermediate allocation to a SparseMatrixCSC, but I want to do it in a way that accords with Julia conventions. Note that getindex(args…; kwargs…) does not allow using kwargs with the bracket syntactic sugar.

The reason why I am asking is because I have defined my own array type such that it would be computationally cheaper if I could skip the intermediate getindex type. I would like something like:

typeof(my_arr) <: MyArrayType
typeof(getindex_as_vec(my_arr, 1:2, 1:2)) <: Vector 

But I don’t want to write the function name getindex_as_vec if there is some convention I should be adhering to.

I think I am an idiot. I think I merely need to use views. e.g. vec(view(myarra, 1:2, 1:2))

1 Like

You probably want to be careful with views of sparse arrays, they don’t have great performance. I’d compare both options, depending on the setting either one may be faster

Here is a solution using CartesianIndices and broadcasting:

using SparseArrays
A = sparse([1 0 1; 0 1 0 ; 0 1 1])
Is = CartesianIndices(A)
@show getindex.(Ref(A), Is[1:2, 1:2])

However looking up a lot of indices in a sparse matrix is not the fastest thing to do. Maybe if you describe your situation a bit more, we could see whether there is a faster approach?

With Sparse arrays, it can sometimes be advantageous to create a copy. You could try the vec∘view, or you could try explicitly collecting it into a new SparseVector. Depending upon your subsequent usage patterns, this may or may not be a win.

1 Like