# Accessing values in a matrix for a column before the first?

I am trying to access elements of the previous columns than first column.

For example in python if i try to access elements before the first column `0` it will return an `empty array`.

``````import numpy as np
x = np.matrix([[ 1,  2, 10],
[ 1,  4, 2],
[ 2,  3,  2],
[ 2,  3,  6]])
a = x[:, 0]
print('\n a is \n', a)
b = x[:, :0]
print('\n b is \n',b)

Output: -->

a is
[


]

b is
[]
``````

But julia does not behave in such manner.

My trial in julia:

``````array = [1 2 3;3 4 5;2 3 4;1 2 3]
a = array[:, 1]
b = array[:, 1-1]

Output :-->

BoundsError: attempt to access 4×3 Array{Int64,2} at index [1:4, 0]

Stacktrace:
 throw_boundserror(::Array{Int64,2}, ::Tuple{Base.Slice{Base.OneTo{Int64}},Int64}) at .\abstractarray.jl:541
 checkbounds at .\abstractarray.jl:506 [inlined]
 _getindex at .\multidimensional.jl:742 [inlined]
 getindex(::Array{Int64,2}, ::Function, ::Int64) at .\abstractarray.jl:1060
 top-level scope at In:1
``````

However, to replicate such operation I tried to implement `try and catch` method and use it over the loop to see what happens when i try accessing different columns. The output is always an empty array.

``````for i in 1:3
try
b = array[:, :i-1]
catch
b = []
end
println("\b b in \$i is \$b")
end

Output :--->

b in 1 is Any[]
b in 2 is Any[]
b in 3 is Any[]
``````

May I know how can I access row elements from `first_column - 1` to `last_column - 1`, where `first_column - 1` returns an empty array but rest returns data from the matrix.

Is this what you want?

``````julia> array = [1 2 3;3 4 5;2 3 4;1 2 3]
4×3 Matrix{Int64}:
1  2  3
3  4  5
2  3  4
1  2  3

julia> array[:, 1:0]
4×0 Matrix{Int64}
``````
2 Likes

Thanks @ettersi , yes this is amazing.

@ettersi, the empty column output seems to be just the result of indexing with an empty array and not with a previous non-existing column index.
Empty columns are thus produced by:

``````array = [1 2 3;3 4 5;2 3 4;1 2 3]

array[:, 1:0]
array[:, 2:1]
array[:, []]

# above empty indexing always produces:
4×0 Matrix{Int64}
``````
1 Like

If understanding this correctly, the following might be closer to OP’s question?

``````array = [1 2 3;3 4 5;2 3 4;1 2 3]
ix = 1:size(array,2)

i = 2
array[:, (i-1 in ix) ? i-1 : []]
4-element Vector{Int64}:
1
3
2
1

i = 1
array[:, (i-1 in ix) ? i-1 : []]
4×0 Matrix{Int64}
``````
1 Like