Write two functions in Julia!

We will write two functions in Julia to demonstrate how they work.

The first function is sumdiff, which will sum up of differences between two vectors

In [1]:
# this bit is all a comment / string. 
"""
`sumdiff`
=========
computes the sum of differences between two vectors 
without creating a third vector in the middle.

Functions
---------
- `sumdiff(x,y)` Computes the sum of x-y where x and y are vectors

Example
-------
~~~~
x = [1 2 3]
y = [3 2 1]
@show sumdiff(x,y)
~~~~
"""
function sumdiff(x,y)
end
Out[1]:
sumdiff (generic function with 1 method)
In [2]:
?sumdiff
search: sumdiff

Out[2]:

sumdiff

computes the sum of differences between two vectors without creating a third vector in the middle.

Functions

  • sumdiff(x,y) Computes the sum of x-y where x and y are vectors

Example

x = [1 2 3]
y = [3 2 1]
@show sumdiff(x,y)
In [3]:
x = [1 2 3]
y = [3 2 1]
@show sumdiff(x,y)
sumdiff(x,y) = 0.0
Out[3]:
0.0
In [4]:
sum(x-y)
Out[4]:
0
In [6]:
sumdiff([1,2,3,4,5,7,8,9],[1 2 3 4 5])
LoadError: BoundsError: attempt to access 1x5 Array{Int64,2}:
 1  2  3  4  5
  at index [6]
while loading In[6], in expression starting on line 1

 in sumdiff at In[1]:24
In [15]:
function diagsolve(A,b)
    for i=1:length(b)
        x[i] = b[i] / A[i]
    end
end
A = diagm([2,3,4.])
b = [1. 1. 1.]
diagsolve(A,b)
LoadError: UndefVarError: x not defined
while loading In[15], in expression starting on line 8

 in diagsolve at In[15]:3