-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
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
Slicing an array creates a copy instead of a reference #6988
Comments
This is the intended behavior, but it's probably going to change. See #5556. For now, I think you need to use |
Well, that's disappointing. |
How would it work exactly? Here's what I'm trying to do; I'm using NLopt.jl and it's API requires all the data is given as a big Vector (in my case it's of size 5_N_N). The data is actually made of 5 NxN Float64 matrices. So I need to find a way of re-interpreting the original Vector in terms of five N*N matrices. And I should be able to work on the original data (to work with NLopt's C code), not a copy of the data. Is there a way of achieving this in Julia today? |
Just tried |
You can simply call |
Sorry, I'm not that familiar with Julia, what is a 3d array? How do I do that exactly? Also, doesn't |
Can you give me a working code? |
Try this, it doesn't copy the arrays: # Vector you get from NLopt (here with 2 5x5 matrices)
julia> a = rand(2 * 25)
# 3-dimensional array holding your 5x5 matrices
julia> b = reshape(a, (5, 5, 2))
# Extract the first 5x5 matrix
julia> c = sub(b, :, :, 1) EDIT: fix the order of dimensions. |
Thanks, but it gives 2x5 matrix instead of a 5x5 matrix. Chaning (2, 5, 5)->(5, 5,2) did the job. |
Just another quick question; the type of the result is Would there be any performance penalties with this abstraction? Or is the optimizer clever enough to optimize this thing as a normal, contiguous array? |
Sub arrays are not known for their performance. I think the ArrayViews from #5556, is likely to have better performance. |
Duplicate of #3701. |
Please check out ArrayViews package at this point, which provides what you want (a performant non-copying view). |
If you need to be sure data is referenced in-place, you can hack around with |
I'm in the middle of a migration from C++ and I'm having a hard time in understanding Julia "slices".
I have a vector
a
. When I dob=a[1:2]
andb[1] = 10
for example,a
is not affected.That is, the "slicing" operation
a[1:2]
creates a copy instead of working with the original data.Is this a bug or intended behavior?
If it is intended behavior, what is the correct way of getting a reference to a piece of the original vector? (whose type is still Vector, not SubArray; I have functions with explicit type annotations for type safety).
The text was updated successfully, but these errors were encountered: