Mason
Mason

Reputation: 3051

Printing variable subscripts in Julia

Hey so I know that due to the Unicode support in Julia one, may write for instance the letter a with the subscript 1 by typing a\_1<TAB>. Now, what if I wanted to do something like the following:

for i in [1 2 3]
    println("a\_i")
end

and have the output be written as

a₁
a₂
a₃

How would I go about this without writing out all the possible subscripts myself?

Upvotes: 2

Views: 2979

Answers (3)

Nathan Boyer
Nathan Boyer

Reputation: 1474

Building off the other answers here, I wrote a set of functions to allow for negative numbers and to work with the more complex superscript case.

function subscriptnumber(i::Int)
    if i < 0
        c = [Char(0x208B)]
    else
        c = []
    end
    for d in reverse(digits(abs(i)))
        push!(c, Char(0x2080+d))
    end
    return join(c)
end

function superscriptnumber(i::Int)
    if i < 0
        c = [Char(0x207B)]
    else
        c = []
    end
    for d in reverse(digits(abs(i)))
        if d == 0 push!(c, Char(0x2070)) end
        if d == 1 push!(c, Char(0x00B9)) end
        if d == 2 push!(c, Char(0x00B2)) end
        if d == 3 push!(c, Char(0x00B3)) end
        if d > 3 push!(c, Char(0x2070+d)) end
    end
    return join(c)
end
julia> for i in [1 -2 39]
           println("a"*superscriptnumber(i))
           println("a"*subscriptnumber(i))
       end
a¹
a₁
a⁻²
a₋₂
a³⁹
a₃₉

Upvotes: 1

improbable
improbable

Reputation: 326

Bogumił Kamiński's answer seems the neatest, but I needed to reverse the order to get the correct string for two-digit numbers:

subscript(i::Integer) = i<0 ? error("$i is negative") : join('₀'+d for d in reverse(digits(i)))

for i=7:13 println("a"*subscript(i)) end

Upvotes: 4

Liso
Liso

Reputation: 2260

You could do this (at least in version 0.6):

ltx = Base.REPLCompletions.latex_symbols

for i in 1:3 
    println("a$(ltx["\\_$i"])") 
end

Upvotes: 8

Related Questions