Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the preferred way to evoke similar on MArrays? #1160

Closed
MilesCranmer opened this issue May 11, 2023 · 3 comments
Closed

What is the preferred way to evoke similar on MArrays? #1160

MilesCranmer opened this issue May 11, 2023 · 3 comments

Comments

@MilesCranmer
Copy link

I am 99% sure someone has posted about this before but I couldn't find it. Please link if you know.

I wrote generic code for AbstractArrays in my library, and use similar to construct arrays of the same container and eltype. All of the arrays I deal with are mutable.

However, it seems that there is weird behavior for MArray:

X = MMatrix{5,100}(rand(5, 100));

We can use similar just fine if we want the same array shape:

julia> typeof(similar(X))
MMatrix{5, 100, Float64, 500}

however, if I want a similar array to a slice of X, it gives me a regular Vector:

julia> typeof(similar(X, 100))
Vector{Float64}

If I try to use @view instead:

julia> typeof(similar(@view X[1, :]))
SizedVector{100, Float64, Vector{Float64}}

rather than an MArray. (Creating a copy with X[1, :] is too slow)

Why is this?

Thanks,
Miles

@MilesCranmer
Copy link
Author

Okay it looks like I am able to get away with:

similar(X, axes(X, 2))

is this the right way to do it?

@mateuszbaran
Copy link
Collaborator

Yes, using axes is the preferred way to get a similar array of a different shape.

@MilesCranmer
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants