Reputation: 2081
Coming from R
I am used to do something like this to get the first element of vector a
:
a <- c(1:3, 5)
a[1]
[1] 1
H can I get the 1
in Julia
? The first element of a
is now a range
.
a = [1:3, 5]
a[1]
1-element Array{UnitRange{Int64},1}:
1:3
Upvotes: 5
Views: 1917
Reputation: 33249
The core problem here is that c(1:3, 5)
in R and [1:3, 5]
in Julia do not do the same thing. The R code concatenates a vector with an integer producing a vector of four integers:
> c(1:3, 5)
[1] 1 2 3 5
The Julia code constructs a two-element vector whose elements are the range 1:3
and the integer 5
:
julia> [1:3, 5]
2-element Vector{Any}:
1:3
5
julia> map(typeof, ans)
2-element Vector{DataType}:
UnitRange{Int64}
Int64
This vector has element type Any
because there's no smaller useful common supertype of a range and an integer. If you want to concatenate 1:3
and 5
together into a vector you can use ;
inside of the brackets instead of ,
:
julia> a = [1:3; 5]
4-element Vector{Int64}:
1
2
3
5
Once you've defined a
correctly, you can get its first element with a[1]
just like in R. In general inside of square brackets in Julia:
Comma (,
) is only for constructing vectors of the exact elements given, much like in Python, Ruby, Perl or JavaScript.
If you want block concatenation like in R or Matlab, then you need to use semicolons/newlines (;
or \n
) for vertical concatenation and spaces for horizontal concatenation.
The given example of [1:3; 5]
is a very simple instance of block concatenation, but there are significantly more complex ones possible. Here's a fancy example of constructing a block matrix:
julia> using LinearAlgebra
julia> A = rand(2, 3)
2×3 Matrix{Float64}:
0.895017 0.442896 0.0488714
0.750572 0.797464 0.765322
julia> [A' I
0I A]
5×5 Matrix{Float64}:
0.895017 0.750572 1.0 0.0 0.0
0.442896 0.797464 0.0 1.0 0.0
0.0488714 0.765322 0.0 0.0 1.0
0.0 0.0 0.895017 0.442896 0.0488714
0.0 0.0 0.750572 0.797464 0.765322
Apologies for StackOverflow's lousy syntax highlighting here: it seems to get confused by the postfix '
, interpreting it as a neverending character literal. To explain this example a bit:
A
is a 2×3 random matrix of Float64
elementsA'
is the adjoint (conjugate transpose) of A
I
is a variable size unit diagonal operator0I
is similar but the diagonal scalar is zeroThese are concatenated together to form a single 5×5 matrix of Float64
elements where the upper left and lower right parts are filled from A'
and A
, respectively, while the lower left is filled with zeros and the upper left is filled with the 3×3 identity matrix (i.e. zeros with diagonal ones).
Upvotes: 7
Reputation: 2311
In this case, your a[1] is a UnitRange collection. If you want to access an individual element of it, you can use collect
For example for the first element,
collect(a[1])[1]
Upvotes: 2