arraysjuliaflat

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].

How do I achieve the same in Julia for 1-D array??

I have a variable A and B:

julia> A
5×1 Array{Int64,2}:
 10
 20
 30
 40
 50

julia> B
2-element Array{Int64,1}:
 1
 3
 5

when I execute this A[[B]]

ERROR: ArgumentError: invalid index: Array{Int64,1}[[1, 2]]

HOWEVER, this statement provides this result:

julia> A[[1, 3 ,5]]
3-element Array{Int64,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.


Solution

  • 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.