Reabo
Reabo

Reputation: 87

Julia: How can I make this repeated conditional statement code shorter?

I want to create 15 dummy variables and use them in the following code, which I like to make it shorter as well. So the question is that how can I make this 15 dummy variables without using D1=zeros(3300), ..., D15=zeros(3300).

Also, how can I make this more compact?

for i=1:3300
    if dt[i,2]==1 D1[i]=1 end
    if dt[i,2]==2 D2[i]=1 end
    if dt[i,2]==3 D3[i]=1 end
    if dt[i,2]==4 D4[i]=1 end
    if dt[i,2]==5 D5[i]=1 end
    if dt[i,2]==6 D6[i]=1 end
    if dt[i,2]==7 D7[i]=1 end
    if dt[i,2]==8 D8[i]=1 end
    if dt[i,2]==9 D9[i]=1 end
    if dt[i,2]==10 D10[i]=1 end
    if dt[i,2]==11 D11[i]=1 end
    if dt[i,2]==12 D12[i]=1 end
    if dt[i,2]==13 D13[i]=1 end
    if dt[i,2]==14 D14[i]=1 end
    if dt[i,2]==15 D15[i]=1 end
end

Upvotes: 1

Views: 103

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69839

I would recommend not to create variables D1 to D15 directly, but rather keep them in a vector of vectors and assign to them like this:

D = [zeros(3300) for i in 1:15]
for i in 1:3300
    D[dt[i,2]][i] = 1
end

Now D[i] is an equivalent of your Di.

And if you really want to have Di variables in global scope you can later write for example:

for i in 1:15
    eval(:($(Symbol("D", i)) = D[$i]))
end

and you will get Di variables.



The : character has two syntactic purposes in Julia. The first form creates a Symbol, an interned string used as one building-block of expressions:

julia> :foo
:foo

julia> typeof(ans)
Symbol

The second is the Range operator. a:b constructs a range from a to b with a step size of 1 (a UnitRange) , and a:s:b is similar but uses a step size of s (a StepRange).


Julia allows interpolation into string literals using $, as in Perl:

julia> "$greet, $whom.\n"
"Hello, world.\n"

julia> "1 + 2 = $(1 + 2)"
"1 + 2 = 3"

In a similar way you can interpolate into expressions e.g.:

julia> x = 1
1

julia> :(x = $x)
:(x = 1)

Symbol Creates a Symbol by concatenating the string representations of the arguments together.

julia> Symbol("my", "name")
:myname

Upvotes: 7

Related Questions