initialize Convex.MaxAtom array Julia

45 views Asked by At

How can I create an Array of Convex.MaxAtoms (or for that matter, other Convex types) with the Convex package? I'm not sure if an Array is the right structure, but what I want to do is initialize something my_array of length n so that I can update each element in a loop like

using Convex
v = Variable(n)
w = Variable(n)
my_array = ...initialized array?...
for i = 1:n
    my_array[i] = max(v[i],w[i])
end

I've tried doing

my_array = Convex.MaxAtom[]
for i = 1:n
    push!(x, max(v[i], w[i]))
end

but I want to avoid reallocating memory and do it upfront. I feel that I must be missing an important part of Julia in not understanding what types to use to construct this.

1

There are 1 answers

0
Dan Getz On BEST ANSWER

In Julia Vector{AnyType}(n) (replace AnyType with a valid type in the application) allocates a vector of uninitialized AnyType elements of length n. More generally, Array{AnyType,3}(2,3,4) would allocate a 3-dimensional tensor of size 2x3x4 and analogously any dimension or shape can be allocated.

For the case in the question, a solution would be:

a = Vector{Convex.MaxAtom}(n)

P.S. the elements are allocated but uninitialized, this is fast, but it may be safer to use fill(some_value, n) or zero(AnyType, n) (which requires zero(AnyType) to be defined).