# 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 [9]:
# 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)
n = length(x)
@assert length(y) == n
d = 0.
for i=1:n
d += x[i] - y[i]
end
return d
end

Out[9]:
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 [10]:
sumdiff([1,2,3,4,5,7,8,9],[1 2 3 4 5])

LoadError: AssertionError: length(y) == n

in sumdiff at In[9]:22
In [18]:
"""
diagsolve
===========

This function will pretend an input matrix is diagonal and solve the linear system
Ax = b

Function
--------
* diagsolve(A,b) takes an input matrix A and a vector b and only uses the diagonal elements of b

Examples
--------
~~~~
A = diagm(randn(5))
b = ones(5)
@show x = diagsolve(A,b)
@show y = A\b  # this should be the same thing
~~~~
"""
function diagsolve(A,b)
x = zeros(length(b))
for i=1:length(b)
x[i] = b[i] / A[i,i]
end
return x
end
A = diagm([2,3,4.])
b = [1. 1. 1.]
diagsolve(A,b)

Out[18]:
3-element Array{Float64,1}:
0.5
0.333333
0.25