# How to get the Cartesian indices of a row/column in a `Matrix`?

Given a `Matrix` `m`, setting its values is simple:

``````m = rand(4, 4)
m[begin, :] = 1
m[:, end] = 2
``````

But how can we get the indices of its first row/last column of elements? I guess it is similar to this question: Eachindex for individual axes of multidimensional arrays. I want something like `eachindex(m, firstindex(m), :)`, but with Cartesian indices.

Another similar question: How to get linear indices of array along a slice k?

1 Like

I guess `axes` does work (as suggested in Eachindex for individual axes of multidimensional arrays?), even for `OffsetArrays`:

`````` using OffsetArrays: OffsetMatrix, Origin

julia> a = OffsetMatrix(rand(4, 4), Origin(0))
4×4 OffsetArray(::Matrix{Float64}, 0:3, 0:3) with eltype Float64 with indices 0:3×0:3:
0.555166  0.773755  0.441709  0.337798
0.201427  0.542714  0.626299  0.518176
0.998011  0.735479  0.894207  0.99043
0.826478  0.261973  0.890299  0.484077

julia> for j in axes(a, 2)
@show CartesianIndex(firstindex(a, 1), j)
end
CartesianIndex(firstindex(a, 1), j) = CartesianIndex(0, 0)
CartesianIndex(firstindex(a, 1), j) = CartesianIndex(0, 1)
CartesianIndex(firstindex(a, 1), j) = CartesianIndex(0, 2)
CartesianIndex(firstindex(a, 1), j) = CartesianIndex(0, 3)

julia> for i in axes(a, 1)
@show CartesianIndex(i, lastindex(a, 2))
end
CartesianIndex(i, lastindex(a, 2)) = CartesianIndex(0, 3)
CartesianIndex(i, lastindex(a, 2)) = CartesianIndex(1, 3)
CartesianIndex(i, lastindex(a, 2)) = CartesianIndex(2, 3)
CartesianIndex(i, lastindex(a, 2)) = CartesianIndex(3, 3)
``````

Also, using `CartesianIndices` seems to be simpler and more consistent with my example:

``````julia> CartesianIndices(a)[begin, :]
4-element OffsetArray(::Vector{CartesianIndex{2}}, 0:3) with eltype CartesianIndex{2} with indices 0:3:
CartesianIndex(0, 0)
CartesianIndex(0, 1)
CartesianIndex(0, 2)
CartesianIndex(0, 3)

julia> CartesianIndices(a)[:, end]
4-element OffsetArray(::Vector{CartesianIndex{2}}, 0:3) with eltype CartesianIndex{2} with indices 0:3:
CartesianIndex(0, 3)
CartesianIndex(1, 3)
CartesianIndex(2, 3)
CartesianIndex(3, 3)
``````

Am I using the correct way to do it?

That’s how I would do it (I don’t know of a better way).

… and `@view ` may be prepended to it.