I can't figure out how to get specific elements/ values of a ket vector in Julia language. I tried to call a specific index of the ket vector using [index], like one does with a regular vector, but that does not seem to work with kets.
Kets are available in the QuantumOptics.jl package. So for a simple example, if I would define a ket myself:
basis = FockBasis(2)
x = Ket(basis, [1,3,2])
which gives output:
Ket(dim=3)
basis: Fock(cutoff=2)
1.0
3.0
2.0
If I then try to get an element of the ket, I would try it like this:
x[1]
which gives an error:
MethodError: no method matching getindex(::Ket{FockBasis{Int64},Array{Int64,1}}, ::Int64)
and I can't access the seperate elements of the ket.
Maybe the easiest way to get the j coefficient for a ket is just to access the j value for the data property of the ket. For your example you can just do
j = 1
j_coeff = x.data[j]
I am currently trying some functionalities of Julia regarding symbolic expressions. Coming from Matlab I searched the documentation for symbolic something with little success until I found some info about the expr = :(<content>) notation.
I started with the declaration of my first function : fun1 = :(1-x) which works fine. However, I need to reuse my expression or manipulations of it afterwards.
After searching a bit, I still did not find a way to say e.g fun2 = -fun1. How does one manipulate expressions once they are declared?
EDIT My example statement being a bit restrictive, an additional case would be the construction of a array of expression using pre-declared expresions as in exprarray = [fun1 0 -2*fun2+3]
you can interpolate expressions with $:
julia> fun1 = :(1-x)
:(1 - x)
julia> fun2 = :(-$fun1)
:(-((1 - x)))
EDIT
The same works for the array :
julia> exprarray = :([$fun1 0 -2*$fun2+3])
:([1 - x 0 -2 * -((1 - x)) + 3])
How can I translate the following code of R to Julia? I am new in Julia.
I know Julia has different ways to replace for loop.
max_trial <- max(dataframe[,1])
max_c1 <- NA
for(c in 1:max_trial){
c1 <- which(dataframe[,1]==c)
max_measure <- max(dataframe[c1,2])
max_c1[c] <- max_measure
}
As suggested I applied the following code translate
max_c1= []
for c in 1:max_trial
c1 = findall(dataframe[:,1] .== c)
max_c1[c] = maximum(dataframe[c1,2])
end
But I received the following error
ERROR: BoundsError: attempt to access 0-element Array{Any,1} at index [1]
Also the values received from this translation “ maximum(dataframe[c1,2])” is still different than The R code. It seems for this part of error some adjustment of the syntax needs improvement.
I think the corresponding Julia code would look like
for c in 1:max_trial
c1 = findall(dataframe[:,1] .== c)
max_c1[c] = maximum(dataframe[c1,2])
end
although I think you did not give enough information to completely answer your question, so I'm not really sure. Maybe adding the data you used and the output you are looking for in your question would help?
In Julia it is possible to create arrays of any size using the functions zeros(.) or ones(.). Is there a similar function to create an array that is filled with nothing at initialization but also accepts floats? I mean a function like in this example:
a = array_of_nothing(3)
# a = [nothing,nothing,nothing]
a[1] = 3.14
# a = [3.14,nothing,nothing]
I tried to find information on internet, but without success... Sorry, I am a beginner in Julia.
The fill function can be used to create arrays of arbitrary values, but it's not so easy to use here, since you want a Vector{Union{Float64, Nothing}}. Two options come to mind:
A comprehension:
a = Union{Float64, Nothing}[nothing for _ in 1:3];
a[2] = 3.14;
>> a
3-element Array{Union{Nothing, Float64},1}:
nothing
3.14
nothing
Or ordinary array initialization:
a = Vector{Union{Float64, Nothing}}(undef, 3)
fill!(a, nothing)
a[2] = 3.14
It seems that when you do Vector{Union{Float64, Nothing}}(undef, 3) the vector automatically contains nothing, but I wouldn't rely on that, so fill! may be necessary.
I think you are looking for the Base.fill — Function.
fill(x, dims)
This creates an array filled with value x.
println(fill("nothing", (1,3)))
You can also pass a function Foo() like fill(Foo(), dims) which will return an array filled with the result of evaluating Foo() once.
I have:
z = data.frame(x1=a, x2=b, x3=c, etc)
I am trying to do:
for (i in 1:10)
{
paste(c('N'),i,sep="") -> paste(c('z$x'),i,sep="")
}
Problems:
paste(c('z$x'),i,sep="") yields "z$x1", "z$x1" instead of calling the actual values. I need the expression to be evaluated. I tried as.numeric, eval. Neither seemed to work.
paste(c('N'),i,sep="") yields "N1", "N2". I need the expression to be merely used as name. If I try to assign it a value such as paste(c('N'),5,sep="") -> 5, ie "N5" -> 5 instead of N5 -> 5, I get target of assignment expands to non-language object.
This task is pretty trivial since I can simply do:
N1 = x1...
N2 = x2...
etc, but I want to learn something new
I'd suggest using something like for( i in 1:10 ) z[,i] <- N[,i]...
BUT, since you said you want to learn something new, you can play around with parse and substitute.
NOTE: these little tools are funny, but experienced users (not me) avoid them.
This is called "computing on the language". It's very interesting, and it helps understanding the way R works. Let me try to give an intro:
The basic language construct is a constant, like a numeric or character vector. It is trivial because it is not different from its "unevaluated" version, but it is one of the building blocks for more complicated expressions.
The (officially) basic language object is the symbol, also known as a name. It's nothing but a pointer to another object, i.e., a token that identifies another object which may or may not exist. For instance, if you run x <- 10, then x is a symbol that refers to the value 10. In other words, evaluating the symbol x yields the numeric vector 10. Evaluating a non-existant symbol yields an error.
A symbol looks like a character string, but it is not. You can turn a string into a symbol with as.symbol("x").
The next language object is the call. This is a recursive object, implemented as a list whose elements are either constants, symbols, or another calls. The first element must not be a constant, because it must evaluate to the real function that will be called. The other elements are the arguments to this function.
If the first argument does not evaluate to an existing function, R will throw either Error: attempt to apply non-function or Error: could not find function "x" (if the first argument is a symbol that is undefined or points to something other than a function).
Example: the code line f(x, y+z, 2) will be parsed as a list of 4 elements, the first being f (as a symbol), the second being x (another symbol), the third another call, and the fourth a numeric constant. The third element y+z, is just a function with two arguments, so it parses as a list of three names: '+', y and z.
Finally, there is also the expression object, that is a list of calls/symbols/constants, that are meant to be evaluated one by one.
You'll find lots of information here:
https://github.com/hadley/devtools/wiki/Computing-on-the-language
OK, now let's get back to your question :-)
What you have tried does not work because the output of paste is a character string, and the assignment function expects as its first argument something that evaluates to a symbol, to be either created or modified. Alternativelly, the first argument can also evaluate to a call associated with a replacement function. These are a little trickier, but they are handled by the assignment function itself, not by the parser.
The error message you see, target of assignment expands to non-language object, is triggered by the assignment function, precisely because your target evaluates to a string.
We can fix that building up a call that has the symbols you want in the right places. The most "brute force" method is to put everything inside a string and use parse:
parse(text=paste('N',i," -> ",'z$x',i,sep=""))
Another way to get there is to use substitute:
substitute(x -> y, list(x=as.symbol(paste("N",i,sep="")), y=substitute(z$w, list(w=paste("x",i,sep="")))))
the inner substitute creates the calls z$x1, z$x2 etc. The outer substitute puts this call as the taget of the assignment, and the symbols N1, N2 etc as the values.
parse results in an expression, and substitute in a call. Both can be passed to eval to get the same result.
Just one final note: I repeat that all this is intended as a didactic example, to help understanding the inner workings of the language, but it is far from good programming practice to use parse and substitute, except when there is really no alternative.
A data.frame is a named list. It usually good practice, and idiomatically R-ish not to have lots of objects in the global environment, but to have related (or similar) objects in lists and to use lapply etc.
You could use list2env to multiassign the named elements of your list (the columns in your data.frame) to the global environment
DD <- data.frame(x = 1:3, y = letters[1:3], z = 3:1)
list2env(DD, envir = parent.frame())
## <environment: R_GlobalEnv>
## ta da, x, y and z now exist within the global environment
x
## [1] 1 2 3
y
## [1] a b c
## Levels: a b c
z
## [1] 3 2 1
I am not exactly sure what you are trying to accomplish. But here is a guess:
### Create a data.frame using the alphabet
data <- data.frame(x = 'a', y = 'b', z = 'c')
### Create a numerical index corresponding to the letter position in the alphabet
index <- which(tolower(letters[1:26]) == data[1, ])
### Use an 'lapply' to apply a function to every element in 'index'; creates a list
val <- lapply(index, function(x) {
paste('N', x, sep = '')
})
### Assign names to our list
names(val) <- names(data)
### Observe the result
val$x