Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let indexing return a matrix instead of a vector in julia

Tags:

matrix

julia

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.

like image 347
Jonas Avatar asked Jun 08 '21 14:06

Jonas


People also ask

How do you make a matrix in Julia?

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

How do you set an index in Julia?

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.

What is matrix indexing?

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.

Is Julia 1 or 0 indexed?

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.


1 Answers

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.

like image 189
Bogumił Kamiński Avatar answered Oct 04 '22 17:10

Bogumił Kamiński