When you index a matrix in Julia, and your selection is a single column or row the result will be represented as a vector. similarly, when you index a single point you get the value of that point, not a 1x1 matrix.
However, for my use case I want my answer to be a matrix as well, because the orientation of the vector has meaning, that I don't want to lose.
So given the following example matrix:
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
I get:
julia> A[:, 1]
2-element Vector{Int64}:
1
3
julia> A[1, :]
2-element Vector{Int64}:
1
2
julia> A[1, 1]
1
but I want:
julia> A[:, 1]
2×1 Matrix{Int64}:
1
3
julia> A[1, :]
1×2 Matrix{Int64}:
1 2
julia> A[1, 1]
1×1 Matrix{Int64}:
1
Is there an easy way to achieve this?
Right now I do something like:
function getindex_asmatrix(A::Matrix, i, j)
# If i & j are Integers convert point to 1x1 Matrix
# If only j == Integer make a nx1 Matrix
# If only i == Integer make a 1xm Matrix
# else do A[i, j]
end
But I feel there might be an more elegant solution.
Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).
Set elements at a given index of array in Julia – setindex!() Method. The setindex!() is an inbuilt function in julia which is used to store values from the given array X within some subset of A as specified by inds.
Indexing into a matrix is a means of selecting a subset of elements from the matrix. MATLAB® has several indexing styles that are not only powerful and flexible, but also readable and expressive. Indexing is a key to the effectiveness of MATLAB at capturing matrix-oriented ideas in understandable computer programs.
Conventionally, Julia's arrays are indexed starting at 1, whereas some other languages start numbering at 0, and yet others (e.g., Fortran) allow you to specify arbitrary starting indices.
Just use 1:1
(range) instead of 1
, e.g.:
julia> A[:, 1:1]
2×1 Matrix{Int64}:
1
3
julia> A[1:1, :]
1×2 Matrix{Int64}:
1 2
julia> A[1:1, 1:1]
1×1 Matrix{Int64}:
1
You could also use [1]
instead, but it will allocate, while 1:1
does not allocate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With