How to access elements of 1-D array through some other 1-D array?
How to access elements of 1-D array through some other 1-D array?
I am very new to Julia, even new to programming. Therefore, please excuse me for simple doubts.
consider the below Matlab Example:
A=[10; 20; 30; 40; 50];
B=[1; 3; 5];
The result of A(B)=0
in the matlab shall be [0.0 20 0.0 40 0.0]
.
A(B)=0
[0.0 20 0.0 40 0.0]
How do I achieve the same in Julia for 1-D array??
I have a variable A
and B
:
A
B
julia> A
5×1 ArrayInt64,2:
10
20
30
40
50
julia> B
2-element ArrayInt64,1:
1
3
5
when I execute this A[[B]]
A[[B]]
ERROR: ArgumentError: invalid index: ArrayInt64,1[[1, 2]]
ERROR: ArgumentError: invalid index: ArrayInt64,1[[1, 2]]
HOWEVER, this statement provides this result:
julia> A[[1, 3 ,5]]
3-element ArrayInt64,1:
5
3
1
Please guide me. I know that Julia has the flat array, but how to access them through any other flat array.
A[[1, 3, 5]]
A[[[1, 3, 5]]]
Hello Crstnbr, Thank you for writing to me. I wish to get the result of Matlab's statement: A(B)=0, in Julia. If I execute this statement: A[B]=0, in Julia, the result is 0; whereas in matlab the result is [0.0 20 0.0 40 0.0].
– NIT_GUP
Sep 8 '18 at 21:35
2 Answers
2
You have an extra pair of brackets.
A[B]
A[ [1; 3; 5] ]
A[ [1, 3, 5] ]
A[ [1 3 5] ]
A[ 1:2:5 ]
all work as desired. You can index an array with any valid index or any collection of indices.
However, A[[B]]
tries to index A
at the location [1;3;5]
, which is an error.
A[[B]]
A
[1;3;5]
You can get your desired result by overwriting the elements of A
at indices given by B
with zeros as follows:
A
B
julia> A=[10; 20; 30; 40; 50];
julia> B=[1; 3; 5];
julia> A[B] .= 0;
julia> A
5-element ArrayInt64,1:
0
20
0
40
0
Here, the dot assignment .=
indicates to change the elements of A in-place.
.=
Okay. That is a very basic thing I didn't know. If I can ask you, is there any good reading source where I can start learning these nuances? I appreciate your help in this. Thanks a lot.
– NIT_GUP
Sep 8 '18 at 21:45
In general, the Julia documentation is fairly easy to read. Have a look here and here for example. I also recommend this blog post
– crstnbr
Sep 8 '18 at 22:14
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi Nit_GUP, it is not really clear to me what you actually want do do. Regarding your error, it is just the difference between
A[[1, 3, 5]]
(works fine) andA[[[1, 3, 5]]]
(errors because a vector of vectors is not a proper vector of indices).– crstnbr
Sep 8 '18 at 20:28