Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia built in function for sum of array?

Tags:

julia

In Julia are there no built in functions to sum an array of numbers?

x = rand(10)
sum(x) # or sum(x, 1)

ERROR: MethodError: objects of type Float64 are not callable

I mean I could write a for loop to sum it as follows,

sum = 0.0    
for i in 1:length(x)
    sum += x[i]
end

but it just surprises me if julia don't have this built in somewhere?

like image 824
Ben10 Avatar asked Jul 31 '17 05:07

Ben10


People also ask

How do you sum an element in an array?

S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.

How do you find the element of an array in Julia?

Using findall() method The findall() method is used to find all the occurrences of the required element from an array, and return an Array (or CartesianArray, depending on the dimensions of input array) of the index, where the elements are present in the input array.

How do you use vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])


1 Answers

As @Michael K. Borregaard mentions, you reasigned the variable sum (exported by default from Base) with the value of a Float64 at some point. When you restated your session, sum was again the Base.sum default, ie:

julia> x = rand(10)         
10-element Array{Float64,1}:
 0.661477                   
 0.275701                   
 0.799444                   
 0.997623                   
 0.731693                   
 0.557694                   
 0.833434                   
 0.90498                    
 0.589537                   
 0.382349        

julia> sum                                                    
sum (generic function with 16 methods)                        

julia> sum(x)               
6.733930084133119 

julia> @which sum(x)                                          
sum(a) in Base at reduce.jl:359     

Notice the warning:

julia> original_sum = sum
sum (generic function with 16 methods)

julia> sum = x[1]                                             
WARNING: imported binding for sum overwritten in module Main  
0.6614772171381087                                                

julia> sum(x)                                                 
ERROR: MethodError: objects of type Float64 are not callable  

julia> sum = original_sum
sum (generic function with 16 methods)

julia> sum(x)               
6.733930084133119  
like image 98
HarmonicaMuse Avatar answered Sep 30 '22 04:09

HarmonicaMuse