how to convert an array{Float64,1} to a Float64? in julia - julia

I just want to know how to convert an array{Float64,1} to a Float64? in julia
utility= rand(1)*row*c*(1-x)
it gives me error "array of size (1,) passed as objective; only scalar objectives are allowed"

Just use rand() instead of rand(1). The former returns a random Float64 value, whereas the latter returns a 1-dimensional array with one element in it. Better to keep everything as scalars in the first place if it's possible to do so.
Generally though, you can't convert a vector v to a scalar. There may be more than one element in it, in which case the conversion isn't well defined. What you can do, however, is index into the vector to extract one of its values.

Related

Return 1-Element Array as Element Type

If I create a Vector of integers
a = Vector(1:3)
and I index one element it has the type of the element
typeof(a[3])
Int64
but if I index one element with a range object it has the type Array
typeof(a[3:3])
Vector{Int64}
How can I make sure that in case of only one element, the element is returned and not the array. The reason is that I want to send the indexed Vector to a function and depending on the type a different method is called.
Why is this happening?
So here's the problem, when you call a[3]
you're actually calling getindex(a, 3)
which has the signature getindex(::AbstractArray, ::Integer).
Your second example is dispatched to a different function, though- getindex(::AbstractArray, ::UnitRange). The behavior of these two functions is different- although they both give what I would expect to see out.
For contrast, both python lists and numpy arrays have the exact same behavior, but it works easier for numpy because numpy doesn't enforce an equal number of dimensions for broadcasting.
What can you do?
First idea: conditional branching using length
a = # ...
return length(a) == 1 ? func(a[1]) : func(a)
Note you can use only(a) instead of a[1] if you're on at least Julia 1.3.
Second idea: if you're programmatically indexing into vector, you could check if the two indices are equal
i = # ... the first index
j = # ... the second index
return i == j ? func(a[i]) : func(a[i:j])
I'm not sure I understand your question correctly, but are you maybe looking for eltype?
julia> eltype(a[3])
Int64
julia> eltype(a[3:3])
Int64
EDIT: Reading #Miles Lucas's answer I see a different interpretation of your question. In this case, the only function might be helpful:
julia> only(a[3])
3
julia> only(a[3:3])
3
Note that this errors if you index with a range longer than 1.

Integer matrix in stan getting flattened

I'm trying to pass a three-dimensional data structure to Stan (in RStan) where the entries must be integers, because a function down-stream requires that. However I'm having trouble declaring it.
I tried the straight-forward approach:
int x[n,n,k];
But that gave me the error
mismatch in number dimensions declared and found in context; ... dims declared=(n,n,k); dims found=(n*n*k)
meaning, clearly, the input array is getting flattened, for some reason (that I don't understand). I'm giving it a simple 3d array, no NAs, the dimensions look right before I pass it. And in fact, the same things is happening for 2d arrays, as well, meaning I can't even declare a set of 2d matrices, as a workaround.
Then I tried
row_vector[K] x[N,N];
but that gives back real, not int. And when I do something like
int row_vector[K] x[N,N];
that's just not proper syntax.
I also tried passing logical values, hoping they'd be re-cast as ints, but no. I passed arrays, I passed them cast with as.matrix, I checked their dimension both before and after being put into the data list.
This is with R version 3.4.1 on OSX 10.11.6, using the most recent version of stan, that was just compiled from source, today.
What am I missing? OR, how might I cast a single real to an integer, so that the integer-requiring function doesn't break?
(And, WHERE is the documentation? The best I can find is long-dead comment threads.)

Function of parameter type in type definition

Assume I want to store I vector together with its norm. I expected the corresponding type definition to be straightforward:
immutable VectorWithNorm1{Vec <: AbstractVector}
vec::Vec
norm::eltype(Vec)
end
However, this doesn't work as intended:
julia> fieldtype(VectorWithNorm1{Vector{Float64}},:norm)
Any
It seems I have to do
immutable VectorWithNorm2{Vec <: AbstractVector, Eltype}
vec::Vec
norm::Eltype
end
and rely on the user to not abuse the Eltype parameter. Is this correct?
PS: This is just a made-up example to illustrate the problem. It is not the actual problem I'm facing.
Any calculations on a type parameter currently do not work
(although I did discuss the issue with Jeff Bezanson at JuliaCon, and he seemed amenable to fixing it).
The problem currently is that the expression for the type of norm gets evaluated when the parameterized type is defined, and gets called with a TypeVar, but it is not yet bound to a value, which is what you really need it to be called with, at the time that that parameter is actually bound to create a concrete type.
I've run into this a lot, where I want to do some calculation on the number of bits of a floating point type, i.e. to calculate and use the number of UInts needed to store a fp value of a particular precision, and use an NTuple{N,UInt} to hold the mantissa.

How to use a vector as a type parameter in Julia

This is similar to my previous question, but a bit more complicated.
Before I was defining a type with an associated integer as a parameter, Intp{p}. Now I would like to define a type using a vector as a parameter.
The following is the closest I can write to what I want:
type Extp{g::Vector{T}}
c::Vector{T}
end
In other words, Extp should be defined with respect to a Vector, g, and I want the contents, c, to be another Vector, whose entries should be the of the same type as the entries of g.
Well, this does not work.
Problem 1: I don't think I can use :: in the type parameter.
Problem 2: I could work around that by making the types of g and c arbitary and just making sure the types in the vectors match up in the constructor. But, even if I completely take everything out and use
type Extp{g}
c
end
it still doesn't seem to like this. When I try to use it the way I want to,
julia> Extp{[1,1,1]}([0,0,1])
ERROR: type: apply_type: in Extp, expected Type{T<:Top}, got Array{Int64,1}
So, does Julia just not like particular Vectors being associated with types? Does what I'm trying to do only work with integers, like in my Intp question?
EDIT: In the documentation I see that type parameters "can be any type at all (or an integer, actually, although here it’s clearly used as a type)." Does that mean that what I'm asking is impossible, and that that only types and integers work for Type parameters? If so, why? (what makes integers special over other types in Julia in this way?)
In Julia 0.4, you can use any "bitstype" as a parameter of a type. However, a vector is not a bitstype, so this is not going to work. The closest analog is to use a tuple: for example, (3.2, 1.5) is a perfectly valid type parameter.
In a sense vectors (or any mutable object) are antithetical to types, which cannot change at runtime.
Here is the relevant quote:
Both abstract and concrete types can be parameterized by other types
and by certain other values (currently integers, symbols, bools, and
tuples thereof).
So, your EDIT is correct. Widening this has come up on the Julia issues page (e.g., #5102 and #6081 were two related issues I found with some discussion), so this may change in the future - I'm guessing not in v0.4 though. It'd have to be an immutable type really to make any sense, so not Vector. I'm not sure I understand your application, but would a Tuple work?

What to use instead of the as.real?

I've start improving some old R code and find that next functions are deprecated:
real creates a double precision vector of the specified length. Each element of the vector is equal to 0.
as.real attempts to coerce its argument to be of double type.
is.real returns TRUE or FALSE depending on whether its argument is of double type or not.
And what to use instead?
Wow, that's pretty old code. I think you'll be fine with double, as.double, and is.double.

Resources