In [1]:
using Dates, Printf
include("printmat.jl") #a function for prettier matrix printing
Out[1]:
In [2]:
fn(x,a,b) = a/x + b #x has to be a scalar for this to work
Out[2]:
In [3]:
X = [1 2;
0 10]
printmat(fn.(X,100,10)) #notice the dot.
In [4]:
X = [1 2;
0 10]
println("X:")
printmat(X)
m = size(X,1)
z = fill(0,m) #to fill with results
for i = 1:m #loop over rows
z[i] = sum(X[i,:]) #or sum(view(X,i,:)) to save memory
end
println("sum of each row:")
printmat(z)
In [5]:
printmat(sum(X,dims=2))
In [6]:
sum(abs2,X,dims=2) #same as sum(abs2.(X),dims=2) but faster
Out[6]:
...or each row (or some other dimension)
The mapslices(fun,x,dims=1) applies fun(x[:,i]) to each column of a matrix x. This is an alternative to looping over the columns.
The cell below illustrates this by calling a function which calculates the moving average of x[t] and x[t-1] for each column of a matrix X.
In [7]:
function MovingAvg2(x) #moving average of t and t-1
T = length(x)
y = fill(NaN,T)
for t = 2:T
y[t] = (x[t] + x[t-1])/2
end
return y
end
X = [1:5 101:105]
Y = mapslices(MovingAvg2,X,dims=1)
println(" X (with 2 columns) and Y (MA(1) of X):")
printmat([X Y])
In [ ]: