Menu
  • HOME
  • TAGS

Julia: Instantiated type parameters

types,julia-lang,type-parameter

It is currently not possible to restrict type parameters like this, though there has been discussion to allow the syntax that you tried up at the top. I believe that the solution that you came up with of checking the type parameter in an inner constructor is considered the best...

Composite types in Julia: Dictionaries as a named field?

dictionary,julia-lang,compositetype

There's a subtle difference in the syntax between types and instances. Dict() instantiates a dictionary, whereas Dict by itself is the type. When defining a composite type, the field definitions need to be of the form symbol::Type. That error message is a little confusing. What it's effectively saying is this:...

how to use the julia language in c++ (visual studio)

julia-lang

Embedding Julia Yes Julia can be embedded in a C or C++ program on all of the platforms which Julia itself is available and in all cases the general approach is the same, but in particular the embedding in Windows is made harder because currently the framework for compilation/embedding (gcc)...

Include an unofficial Julia package in a REQUIRE file?

julia-lang

Unfortunately there is no way to do this at this time, but it is a requested feature. See this Github issue and this mailing list thread.

Julia file input reading speed

performance,optimization,input,julia-lang

So my baseline time on the large input (time cat A-large-practice.in | julia original.jl) was real 0m2.730s user 0m2.683s sys 0m0.351s On my system it takes Julia about 0.2 seconds to start running the file. Putting the code in a function is possibly the most important first step - this...

Julia uninitialize array at particular index

arrays,julia-lang

Undefined values are essentially null pointers, and there's no first-class way to "unset" an array element back to a null pointer. This becomes more difficult with very large arrays since you don't want to have much (or any) overhead for your sentinel values that represent unconnected nodes. On a 64...

Using matplotlib's patches in julia

matplotlib,julia-lang

OK, thanks to jverzani's link, I was able to piece together a working example. I'm still a little shaky on the syntax in Julia for setting all the options for the plot. using PyPlot using PyCall @pyimport matplotlib.patches as patch cfig = figure() ax = cfig[:add_subplot](1,1,1) ax[:set_aspect]("equal") c = patch.Circle([0.5,0.5],0.4,fc="blue",ec="red",linewidth=.5,zorder=0)...

How to construct the POE ensemble in julia

julia-lang

The code is actually correct, you just have the wrong field The eigenvalue result is true for unitary matrices (complex entries); based on the code from section 4.6 of the Edelman and Rao paper, if you replace the first line by X = randn(dim, dim) + im*randn(dim, dim) you get...

Parametric type not working as expected in Julia

julia-lang

This is the expected behavior. Types in Julia are invariant rather than covariant or contravariant. See this section of the manual for a more detailed explanation: http://julia.readthedocs.org/en/latest/manual/types/#man-parametric-types...

Parametric Type Creation

julia-lang

The answer is that things get funky with parametric types and inner constructors - in fact, I think its probably the most confusing thing in Julia. The immediate solution is to provide a suitable outer constructor: using Dates type EconData{T} values::Vector{T} dates::Array{Date} colnames::Array{ASCIIString} function EconData(values, dates, colnames) if size(values, 1)...

Julia: using splat to pass along arguments

julia-lang,splat

Your solution is the preferred way function A(x, y; args...) B(x; args...) C(y; args...) end function B(x; a=0, _...) # catch rest println(x,a) end function C(y; a=0, b=0) println(y,a,b) end A(1, 2) # Works A(1, 2, a=1) # Works A(1, 2, a=1, b=1) # Works Theres no special meaning to...

Julia: @fastmath not defined

julia-lang

Thanks Simon Byrne. My julia version is v0.3.8 less than v0.4. That's why julia prompts "@fastmath not defined".

Julia macros may treat variable and literals differently?

julia-lang

Macros are very different beasts compared to functions. One of the differences is that they do not evaluate their arguments: http://docs.julialang.org/en/latest/manual/metaprogramming/#macro-invocation It is important to emphasize that macros receive their arguments as expressions, literals, or symbols. To see the implications compare the 2 outputs (left as an exercise): julia> macroexpand(:(@load...

Resize HDF5 dataset in Julia

julia-lang,hdf5

The docs have a brief mention of extendible dimensions in hdf5.md excerpted below. You can use extendible dimensions, d = d_create(parent, name, dtype, (dims, max_dims), "chunk", (chunk_dims), [lcpl, dcpl, dapl]) set_dims!(d, new_dims) where dims is a tuple of integers. For example b = d_create(fid, "b", Int, ((1000,),(-1,)), "chunk", (100,)) #-1...

Julia: local in module scope

julia-lang

It's to prevent _F_ from being visible in the global method cache. If you'll call clever_foo with the same n repeatedly, you can do even better by saving the compiled function in a Dict. That way you don't have to recompile it each time....

Julia: How do I create a macro that returns its argument?

macros,julia-lang

The input expression to the macro needs to be quoted because a macro returns an expression, which are evaluated, while you would like to get the expression itself, hence you need an extra quoting. The quoting can be done as: macro mymacro(ex) Expr(:quote,ex) # this creates an expression that looks...

How to parse output of external command in Julia?

parsing,julia-lang

Since readall returns a String, you want something that operates on a String, split fits the bill. Base.split(string, [chars]; limit=0, keep=true) Return an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by "search"'s...

Is it possible to sort a dictionary in Julia?

sorting,dictionary,data-structures,julia-lang

While SortedDict may be useful if it is necessary to keep the dictionary sorted, it is often only necessary to sort the dictionary for output, in which case, the following may be what is required: list1 = [1,2,3,4,5] list2 = [6,7,8,9,19] dictionary1 = Dict(zip(list1,list2)) sort(collect(dictionary1)) ... which produces: 5-element Array{(Int64,Int64),1}:...

Julia way of searching tokens in integer arrays

julia-lang

For practice I have also made trial-and-errors and the following patterns have worked for Julia0.4.0. With A = Int[1,2,3,2,3] and pat = Int[2,3], the first one is x = Int[ A[i:i+1] == pat ? i : 0 for i=1:length(A)-1 ] x[ x .> 0 ] # => [2,4] the second...

Why 2 ^ 3 ^ 4 = 0 in Julia?

julia-lang

I'm surprised I couldn't find a duplicate question about this on SO yet. I figure I'll answer this slightly differently than the FAQ in the manual since it's a common first question. Oops, I somehow missed: Factorial function works in Python, returns 0 for Julia Imagine you've been taught...

Converting images from RGB to HSL and back again with julia

image,colors,type-conversion,julia-lang,color-space

Until Color.jl gets updated and more testing implemented/passed, you can make a single character change in Color/src/conversions.jl to most likely fix this particular issue. Change - to + on line 156. 150 # Everything to HSL 151 # ----------------- 152 153 function convert{T}(::Type{HSL{T}}, c::AbstractRGB) 154 c_min = min(c.r, c.g, c.b)...

Passing a pointer to struct as an argument in Julia

julia-lang

Use Ref{fakeCStruct}: r = Ref(fakeCStruct(3, 4)) ccall((:somefunction, "lib"), Void, (Ref{fakeCStruct},), r) From the Julia docs in the System Independent table here: C name: | Julia base type T* (where T represents an appropriately defined type) | Ref{T} ...

How to get a function from a symbol without using eval?

julia-lang

@Isaiah's answer is spot-on; perhaps even more-so after the edit to the original question. To elaborate and make this more specific to your case: I'd change your NeuralLayer type to be parametric: type NeuralLayer{func_type} weights::Matrix{Float32} biases::Vector{Float32} end Since func_type doesn't appear in the types of the fields, the constructor will...

Gadfly for Julia, plotting multiple dimension in Bar Chart

julia-lang,gadfly

If I understand the question right, you can generate the plot you're looking for (minus the change in alpha value for different months) with using DataFrames, Gadfly data = DataFrame() data[:DrinkType] =["Coke","Coke","Coke","Coke","Pepsi","Pepsi","Pepsi","Pepsi"] data[:Country] = ["UK", "US", "UK", "US","UK", "US", "UK", "US"] data[:Month] = ["April", "April", "March", "March","April", "April", "March", "March"]...

Extend many standard methods to a new custom vector type

julia-lang

Here's an example using Julia's Metaprogramming: for op in (:+, :-, :.<) @eval ($op)(a::MyType, b::MyType) = ($op)(a.x, b.x) end ...

How to plot those equations in julia?

plot,julia-lang

Use for example plot(p1,0,10,p2,0,10,p3,0,10) When plotting a function with Winston you need to specify an xrange for the plot. The example above will generate a plot for an xrange 0...10....

Short circuit evaluation causing an invalid assignment location error

julia-lang

Your error is caused because the && operator has higher precedence than the assignment operator = so your line of code is executed as if you would write (x < 4 && x) = 5. For a solution you have to add parantheses. x < 4 && (x = 5)...

Sapply (from R) equivalent for Julia?

julia-lang

You can use an anonymous function as in mapslices(t -> [mean(t), median(t), iqr(t)], A, 1) but using comprehensions and splatting, as in your last example, is also fine. For very large arrays, you might want to avoid the temporary allocations introduced by transpose and splatting, but in most cases you...

Concatenate ArrayViews (or sliceviews or SubArrays) in Julia?

julia-lang

Not directly. But you could roll your own type with something like: julia> type CView{A<:AbstractArray} <: AbstractArray a::A b::A end julia> import Base: size, getindex, setindex! julia> size(c::CView) = tuple([sa+sb for (sa, sb) in zip(size(c.a), size(c.b))]...) size (generic function with 57 methods) julia> getindex(c::CView, i::Int) = i <= length(c.a) ?...

plot a line in 3D plot in julia

matplotlib,plot,3d,julia-lang

well, I've just had to make: using PyPlot using Distributions function f(x) return (x[1]^2 + x[2]^2) #return sin(x[1]) + cos(x[2]) end n = 100 x = linspace(-1, 1, n) y = linspace(-1,1,n) xgrid = repmat(x',n,1) ygrid = repmat(y,1,n) z = zeros(n,n) for i in 1:n for j in 1:n z[i:i,j:j]...

Constructors in Julia: initializing named fields based on the input value of other named fields

constructor,julia-lang,compositetype

Inner constructors are just the functions that appear inside the type block with the same name as the type. That means that you can use either function syntax to define them. You can use the short form (as you did above), or you can instead use the more verbose block...

Check whether a symbol can be safely evaluated

julia-lang

The HDF5.jl package has to deal with this. It tackles it by parsing the string and then inspecting the result before evaling it. If the parsed string is what it considers to be a valid_type_expression then it knows that it should be safe to evaluate in the Main namespace. This...

Equivalent of gmtime in Julia?

time,timezone,julia-lang,strftime

Looks like gmtime is on Julia's TODO list. Until it gets included, will something like this work for you? julia> function gmtime(t::Real) t = floor(t) tm = TmStruct() ccall(:gmtime_r, Ptr{TmStruct}, (Ptr{Int}, Ptr{TmStruct}), &t, &tm) return tm end gmtime (generic function with 1 method) julia> strftime("%H:%M:%S", gmtime(0)) "00:00:00" ...

Julia's dictionary method `haskey` returning false when key is present

dictionary,equality,julia-lang

But look at this: type Point{T} x::T y::T end P = Point(1., 2.) D = [P => 42] haskey(D, P) evaluates to true. It does work if you use the same object, but it does not work if you use 2 objects with the same field values. Note that objects...

How to construct matrix from row/column vectors in Julia

matrix,julia-lang

Have you tried hcat: julia> column(j) = [j, j ,j] column (generic function with 1 method) julia> my_matrix = hcat([column(j) for j=1:4]...) 3x4 Array{Int64,2}: 1 2 3 4 1 2 3 4 1 2 3 4 ...

A_ldiv_B! with sparse matrices

optimization,linear-algebra,julia-lang,factorization,levenberg-marquardt

It can be a bit tricky to figure out exactly which code path is taken when your are running into code that uses substitutions during parsing as is the case for '. You could try julia> ( J'*J + sqrt(100)*DtD ) \ -J'fcur to see another substitution taking place. I...

Convert/Parse Float64 into String

julia-lang

Use the string function: julia> string(0.5) "0.5" EDIT: For custom formatted strings, you can use the @sprintf macro: julia> @sprintf("%.2f",0.5) "0.50" ...

How could I eliminate more than one row from array in an Julia?

arrays,multidimensional-array,julia-lang

You can use either logical or integer indexing. For example, function eliminate_matching_rows(A, pattern) keep = [A[i,:] != pattern for i = 1:size(A,1)] A[keep, :] end would eliminate all of the rows in A that match pattern....

Julia equivalent of dplyr's bind_cols and bind_rows

r,dplyr,julia-lang

Perhaps Julia's vcat and hcat functions will satisfy your requirements. julia> using DataFrames julia> df1 = DataFrame(a = 1, b = 1) 1x2 DataFrames.DataFrame | Row | a | b | |-----|---|---| | 1 | 1 | 1 | julia> df2 = DataFrame(b = 1, c = 1) 1x2 DataFrames.DataFrame...

Subtypes of composite types

julia-lang

The reason for your results is julias invariant typing system. This means, although ASCIIString <: String is true, Vector{ASCIIString} <: Vector{String} is false. To get around, use parametric types: import Base.ismatch function ismatch{T<:String}(vector::Vector{T}, regex::Regex) [ismatch(regex,string), for string in vector] end ...

Julia parallel programming - Making existing function available to all workers

for-loop,parallel-processing,julia-lang

The approach to return the function seems elegant but unfortunately, unlike JavaScript, Julia does not resolve all the variables when creating the functions. Technically, your training function could produce the source code of the function with literal values for all the trained parameters. Then pass it to each of the...

Memory allocation in a fixed point algorithm

algorithm,julia-lang

I think replacing the following lines in the first code for iter = 1:max_it oldx = copy( x ) ... by oldx = zeros( N ) for iter = 1:max_it oldx[:] = x # or copy!( oldx, x ) ... will be more efficient because no array is allocated. Also,...

How to upgrade Julia to a new release?

julia-lang

1.yeah you're right. Pkg.update() is used for updating julia's packages, not julia itself. So download the prebuild version and install again seems to be the only way to upgrade julia. Or you can build julia by yourself from source https://github.com/JuliaLang/julia. 2.you can find the release notes here: https://github.com/JuliaLang/julia/blob/master/NEWS.md...

Performance of for loops in Julia

performance,for-loop,julia-lang

The answer taking "Is it always better to avoid such top-level variables?" literal is of course "No, it depends", but a useful remark is that declaring global variables as constant const N = 10000000 makes case 2 as fast as case 3....

What is the equation used in R's ccf and Julia's crosscor?

r,julia-lang,cross-correlation

I assume that citing this excerpt here is ok by StackOverflow's terms of use? From page 390 (section 14.1) of Venables and Ripley (2002) you can find the definition that they use here for the acf() function: If you look at the source code of the ccf() function in R...

How to change the Winston plot range of x after evaluation in Julia?

plot,julia-lang

You will also have to re-calculate y and generate a new plot: using Winston x=[0:0.1:2pi]; y=sin(x) plot(x,y) Generates the first plot and then x=[0:0.1:4pi]; #Re-define x y=sin(x) #Calculate new y plot(x,y) #Generate new plot will generate a new plot....

How do I check if a method exists for a particular type?

julia-lang

It turns out that method_exists is (currently) the best way to check whether a method exists for a particular type, but one needs to be very careful. My example above just happened to stumble upon some slightly confusing (but internally consistent) behaviour in Julia's inner workings. Read on if you're...

How do I load a csv file with complex numbers in julia?

csv,julia-lang

Here's one way: julia> b = map(x->eval(parse(x)),readcsv("test.csv")) 2x1 Array{Complex{Float64},2}: 1.0+2.3im 2.3+0.0im ...

Matching of array elements in Julia

julia-lang

To make an element-by-element comparison, Julia requires that both arrays have the same number of elements. This can be achieved in this case with a comprehension: julia> x = Any[[1,2],[2,3],[3,4],[4,5]] 4-element Array{Any,1}: [1,2] [2,3] [3,4] [4,5] julia> x[x.==[[3,4] for i in 1:length(x)]] 1-element Array{Any,1}: [3,4] So the question in my...

Strange observation about timing comparison between Julia and Matlab

performance,matlab,julia-lang

There are a couple of things going on here. Firstly, unlike Matlab, the x is an array of machine integers, not floating point values. This appears to be the main difference in speed, as it is unable to use BLAS routines for linear algebra. You need to do either x...

Problems in training text on AdaGram.jl

machine-learning,julia-lang,word2vec

The package provides a few shell scripts to pre-process the data and fit the model: you have to call them from the shell, i.e., outside Julia. # Install the package julia -e 'Pkg.clone("https://github.com/sbos/AdaGram.jl.git")' julia -e 'Pkg.build("AdaGram")' # Download some text wget http://www.gutenberg.org/ebooks/100.txt.utf-8 # Tokenize the text, and count the words...

What mistake did I make in this matrix multiplication in Julia?

julia-lang

Julia and Matlab actually give the same result (for instance, the bottom-left element is -1.4e-14 in both cases): it is not exactly the identity matrix because floating point arithmetic is not exact. You can explicitly round the result before displaying it. M1 = [ 1 3 4; 45 64 33;...

Type stable functions in Julia for general distribution when working with floating point inputs

types,floating-point,julia-lang

The one and zero functions are useful here: function f(x, c) if x <= 0 return zero(x) elseif x <= c return x/c else return one(x) end end This version is a bit more strict about the input types: function f{T<:FloatingPoint}(x::T, c::T) if x <= 0 return zero(T) elseif x...

Using method source(edge) of Package Graphs.jl in Julia on Juliabox.org

graph,runtime-error,julia-lang

From Julia's Manual: Julia will even let you redefine built-in constants and functions if needed: julia> pi π = 3.1415926535897... julia> pi = 3 Warning: imported binding for pi overwritten in module Main 3 julia> pi 3 julia> sqrt(100) 10.0 julia> sqrt = 4 Warning: imported binding for sqrt overwritten...

Efficient one-liner in Julia to calculate “running” sums?

julia-lang

IIUC, you can use cumsum: julia> block_lengths = [2, 2, 2, 2, 3]; julia> cumsum(block_lengths) 5-element Array{Int32,1}: 2 4 6 8 11 julia> [0; cumsum(block_lengths)] 6-element Array{Int32,1}: 0 2 4 6 8 11 which should be O(N)....

Print columns with variable spacing in Julia

julia-lang

Formatted output to the REPL @sprintf and a loop is probably what you want Assuming test.dat contains the following: A 1 11 AT 2 12 ARE 3 13 Then using the julia @printf macro, which behaves like C printf, the following looks like what you want assuming you want 2...

Calling Win32 Functions From Julia

winapi,julia-lang

Yes you do need to supply a library name. The first argument to ccall is a tuple of the form (:function, "library"). So, if you were calling GetTickCount it would be (:GetTickCount, "kernel32"). You also need to specify the calling convention, return value type, and the parameter types. In the...

Julia metaprogramming return symbol

julia-lang

The symbol your function returned where the symbol function, due to the last symbol in your qoute did not have $ in front. The second problem is you would like to return the symbol it self, which requires you make a quote inside the quote similar to this question Julia:...

Guidelines for writing Julia code future-compatible with v0.4

julia-lang

Its quite possible that there will be a change before release that affects you that will make it impossible to support both. Of the easier fixes, Compat.jl should handle a majority.

Function with no arguments but with type in Julia

function,methods,types,julia-lang

When exploring the behavior of a function in Julia, it is important to understand which specific method is being called. Julia is organized around multiple dispatch, so a single name such as ndims may be associated with different implementations -- chosen by the type of the arguments. To see how...

Exact decimal arithmetic in Julia

floating-point,julia-lang,multiplication

Some options: Use the inbuilt Rational type. The most accurate and fastest way would be 16//100 * 16//100 If you're using very big numbers these might overflow, in which case you can use BigInts instead, big(16)//big(100) * big(16)//big(100) (you don't actually need to wrap them all in bigs, as the...

The command to add to path in Julia language

path,julia-lang

Note: the following paths may be Unix-specific. You can add the file .juliarc.jl to your home directory, and include the line @everywhere push!(LOAD_PATH,"/path/to/my/code") The @everywhere ensures that it will work even if you've started julia with multiple workers....

How do I switch between different versions of Julia (specifically between v0.3 and v0.4 on Ubuntu)?

linux,ubuntu,ubuntu-14.04,julia-lang

You can install different versions of Julia in different locations and set separate symlinks. For example, you could download the v0.3 Linux binaries and install them to one location, then clone the GitHub source for v0.4 and install that in another location. Then set symlinks such as julia3 for v0.3...

How to obtain deep copies of Julia composite types?

julia-lang

An answer to your specific question: When you define a new type in Julia, it is common to extend some of the standard methods in Base to your new type, including deepcopy. For example: type MyType x::Vector y::Vector end import Base.deepcopy Base.deepcopy(m::MyType) = MyType(deepcopy(m.x), deepcopy(m.y)) Now you can call deepcopy...

Populating a julia dictionary with an array of symbols

scope,metaprogramming,julia-lang

The scoping issue that you are running into is that eval always evaluates expressions in global scope (the current module, unless specified otherwise). In this particular case, you could deal with that by using println(obj) instead of eval(:(println("$obj"))); there's no evaluation necessary to look at the symbol itself! But if...

The ternary operator in a one-line function

julia-lang,ternary-operator

julia> f(x::Number) = x < 1 ? 0 : 2 f (generic function with 1 method) julia> f(0) 0 julia> f(1) 2 julia> f(0.99) 0 ...

In Julia, can a macro access the inferred type of its arguments?

julia-lang

Macros cannot do this, but generated functions can. Check out the docs here : http://julia.readthedocs.org/en/latest/manual/metaprogramming/#generated-functions...

How to change radial ticks in julia PyPlot polar plot?

python,matplotlib,plot,julia-lang

I've never used Julia, but you need to set the yticklabels. I think this should do it: ax1[:set_yticks]([0.2,0.4,0.6,0.8,1.0]) ax1[:set_yticklabels](["-40dB","-30dB","-20dB","-10dB","0dB"]) ...

Julia (Julia-lang) conditional in function chaining

function,julia-lang

I discovered the reason was because I did not understand the type being parsed. Here is an example: [3:999] |> println(typeof(x)) # Array{Int64,1} Meaning the value being parsed is an array of integer64. So evaluating the following: [1:999] % 3 == 0 # false So my answer was to instead...

How to display a type alias instead of a parametric type in error messages

julia-lang

You need to define an appropriate show method: import Base.show show(io::IO, ::Type{MT}) = print(io, "MT") Your example then gives: julia> y1 + y2 ERROR: `+` has no method matching +(::MT, ::MT) ...

MessageHandler for Julia

c,rabbitmq,activemq,julia-lang,message-handlers

I'm not aware of one but have only done a cursory search. There are many Julia libraries which simply wrap an existing and well-understood C API. While getting the package build and install correct this way can be slightly tricky, it saves re-implementing complex protocols. There doesn't seem to be...

Function Handles in Julia

callback,function-pointers,julia-lang,function-handle

According to the documentation, the objective function for NLOpt should be of the form: function f(x::Vector, grad::Vector): if length(grad) > 0: ...set grad to gradient, in-place... return ...value of f(x)... end Thus, the code would need to look something like: function myFun(a, b, c, d, grad) a - 3* b...

After building julia from source, what's safe to delete?

make,julia-lang

The /deps folder is not needed, that is correct but the simple thing to do is make install and that will create a directory julia-some hex number. That directory is all that is needed and it can be copied anywhere and everything else deleted afterwards, but the /deps folder will...

Efficient-yet-terse way to add all the arrays in a composite type?

julia-lang

A more julian approach to add_structs_1 is to make the inner loop a separate function, this allows the compiler to specialize the function on each type in the SampleStruct and gives quite a speedup. By profiling the code it was visible that the time to execute names(SampleStruct) were quite significant,...

Fast tensor initialisation in Julia

julia-lang

Knowing nothing of 3D tensors with values of the "diagonal Gaussian", using thesquare comment from the original post, "typing" q (@code_warntype helps here: Big performance jump!), and further specializing the @nloops, this works much faster on the platforms I tried it on. julia> square(x::Float64) = x * x square (generic...

How to get the normal definition of week number with Dates

date,julia-lang

What I ended up doing looks something like this using Dates function getWWFromDate(date) year = Dates.year(date+Dates.Day(6)) #How many days since the start of the first ww of the year startOfFirstWW = Dates.firstdayofweek(Date(year)) - Dates.Day(1) #How many days from the current date to that day? doy = Dates.days(date-startOfFirstWW) ww = floor(doy/7)+1...

Creating an Array of Arrays in Julia

arrays,data-structures,julia-lang

You can construct your array of arrays like so: # Initialize an array that can contain any values listOfLists = Any[] # Push some arrays into the array push!(listOfLists, [1, 2, 3]) push!(listOfLists, [4, 5]) push!(listOfLists, ["Julia", "rocks"]) # You now have an array containing arrays listOfLists # 3-element Array{Any,1}:...

Slicing and broadcasting multidimensional arrays in Julia : meshgrid example

multidimensional-array,slice,julia-lang

Broadcasting in Julia has been modelled pretty much on broadcasting in NumPy, so you should hopefully find that it obeys more or less the same simple rules (not sure if the way to pad dimensions when not all inputs have the same number of dimensions is the same though, since...

Julia: BigFloat Normal distribution

julia-lang,arbitrary-precision,bigfloat

Not directly. My eventual plan is to make Distribution types parametric, which would also allow for Float32 arguments, but that is a while away yet. In the meantime, there is the non-exported φ which gives the result you wanted: Distributions.φ(x) - pdf(Normal(), x_small) ...

Julia indexing Arrays in Vector

indexing,julia-lang

I am using Julia v0.3.5 and this is the error message I see: julia> n = findnext(x[1,1,1],[1,3]) #Crash ERROR: `findnext` has no method matching findnext(::Array{Array{Int64,1},1}, ::Array{Int64,1}) ?findnext reveals that it requires three arguments, A, v, start::Integer. The start is the index to start looking for the element: julia> n =...

How do I create a recursive typealias in julia?

recursion,types,julia-lang,type-alias

Dose this work for what you are doing? typealias NestedTuple0{N,T} Tuple{Union(T,N),Union(T,N)} typealias NestedTuple{T} NestedTuple0{NestedTuple0{T},T} Note: I am only able to try this in 036, not 04 An exmple of use: function rnt(p) np = 0.95*p a=rand() <p ? rnt(np) : 1 b=rand() <p ? rnt(np) : 2 (a,b) end x=rnt(1.0)...

Julia metaprogramming: “ERROR: unsupported or misplaced expression $”

julia-lang

This was a bug, issue filed here: https://github.com/JuliaLang/julia/issues/10997 It has been fixed since. As indicated in the comments on the question, there are some hacky workarounds if you're stuck on an unfixed Julia version, but hopefully you can upgrade....

How do I load a UTF16-encoded text file in Julia?

unicode,julia-lang

The simplest way is to read it as bytes and then convert: s = open(filename, "r") do f utf16(readbytes(f)) end Note that utf16 also checks for a byte-order-mark (BOM), so it will deal with endianness issues and won't include the BOM in the resulting s. If you really want to...

julia @printf changes my variable

julia-lang

Macro parsing (particularly within the context of a function call) is a little finicky. You can see how Julia parsed this simply by quoting it: julia> :(annotate(@printf "test : %5.2f" b, xy=[1;1])) :(annotate(@printf "test : %5.2f" (b,xy) = [1,1])) As you can see, the macro is "greedier" than function arguments....

Compiler messages in Julia

julia-lang

In this case it's almost certainly a consequence of inlining: your printLength function is so short, it's almost certainly inlined into the call site, which is why you get the line number 8. Eventually, it is expected that inlining won't cause problems for backtraces. At the moment, your best bet---if...

Can I use a subtype of a function parameter in the function definition?

julia-lang

The ability to define a function g{T, S<:T}(::T, ::S) has been referred to as "triangular dispatch" as an analogy to diagonal dispatch: f{T}(::T, ::T). (Imagine a table with a type hierarchy labelling the rows and columns, arranged such that the super types are to the top and left. The rows...

Juno IDE for Julia, how to interact?

ide,julia-lang

You can't enter commands into the console in Juno--that's for displaying output. Commands can be submitted from within the editor by setting your cursor in the line to submit and pressing Ctrl+Enter or Shift+Enter. The value will then be displayed in a small popup next to the line and the...

Speeding up `using Distributions` in Julia

julia-lang

Static precompilation might happen for Julia 0.4, not 100% clear yet if it'll make it in. If you'd like to do it somewhat manually by baking it into your "system image", check out the handy package SystemImageBuilder.jl....

How to get more info on julia array bounds error?

julia-lang

Bounds error reporting has improved in julia v0.4 via this pull request https://github.com/JuliaLang/julia/pull/9534. In julia 0.4 the array as well as the index you were trying to access get printed by default: julia> wrong() ERROR: BoundsError: attempt to access 158x4 Array{Float64,2}: NaN 0.0 0.0 0.0 0.0157085 0.0 0.0 0.0 0.0314201...

How can I write code to work with 1D matrices in Julia?

julia-lang

Quoting from your follow-up comment: B is sometimes a matrix, sometimes a vector/1D matrix - that's the problem. You can convert a vector to a 2D array with the "slicing" operation [:;:]. In other words, if B has type Array{T,1}, then B[:,:] has type Array{T,2}: julia> B = [1; 2]...

How to return values from recursive function to array

recursion,julia-lang

This is certainly not optimal, but it's functional. julia> function nested_loop{T <: Integer, V <: AbstractVector}(depth::T, n::T, symb_arr::V, len::T, k::T, num_arr::V, result::Array{V,1}) for i = k:len num_arr[depth-n+1] = symb_arr[i] n == 1 ? push!(result, deepcopy(num_arr)) : nested_loop(depth, n-1, symb_arr, len, i, num_arr, result) end end nested_loop (generic function with 1...

Overloading a function in two files (in Julia)

julia-lang,multiple-dispatch

You have to make A.f and B.f the same function (in the example above they are just different functions with the same name). Then you can overload one method in each of the modules and multiple dispatch will do its job. The way to achieve this is either to have...

Matrix optimization in NLopt

vectorization,julia-lang,nlopt

Yes, NLopt only understands vectors of decision variables. If your code is more naturally expressed in terms of matrices, then you should convert the vector into a matrix in the function and derivative evaluation callbacks using reinterpret.

Operating in parallel on a large constant datastructure in Julia

performance,parallel-processing,julia-lang,hpc

This should get you started: function get_chunks(data::Vector, nchunks::Int) base_len, remainder = divrem(length(data),nchunks) chunk_len = fill(base_len,nchunks) chunk_len[1:remainder]+=1 #remained will always be less than nchunks function _it() for ii in 1:nchunks chunk_start = sum(chunk_len[1:ii-1])+1 chunk_end = chunk_start + chunk_len[ii] -1 chunk = data[chunk_start: chunk_end] produce(chunk) end end Task(_it) end function r_chunk_data(data::Vector) all_chuncks...