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
# 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
?sumdiff
x = [1 2 3]
y = [3 2 1]
@show sumdiff(x,y)
sum(x-y)
sumdiff([1,2,3,4,5,7,8,9],[1 2 3 4 5])
"""
`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)