aboutsummaryrefslogtreecommitdiffstats
path: root/julia/ndgrid.jl
diff options
context:
space:
mode:
authorAaron LI <aaronly.me@gmail.com>2016-03-31 10:57:34 +0800
committerAaron LI <aaronly.me@gmail.com>2016-03-31 10:57:34 +0800
commitc9c896dea2ba43551c4e10bd49666105449e9bd7 (patch)
treee94b73f17b2d776c2acd4c9549657f500c3dc7ce /julia/ndgrid.jl
parent2b6cb9b655a53d43b32a8a211287c82f4f59999a (diff)
downloadatoolbox-c9c896dea2ba43551c4e10bd49666105449e9bd7.tar.bz2
add all scripts/tools
Diffstat (limited to 'julia/ndgrid.jl')
-rw-r--r--julia/ndgrid.jl52
1 files changed, 52 insertions, 0 deletions
diff --git a/julia/ndgrid.jl b/julia/ndgrid.jl
new file mode 100644
index 0000000..688a246
--- /dev/null
+++ b/julia/ndgrid.jl
@@ -0,0 +1,52 @@
+# This file is a part of Julia. License is MIT: http://julialang.org/license
+
+ndgrid(v::AbstractVector) = copy(v)
+
+function ndgrid{T}(v1::AbstractVector{T}, v2::AbstractVector{T})
+ m, n = length(v1), length(v2)
+ v1 = reshape(v1, m, 1)
+ v2 = reshape(v2, 1, n)
+ (repmat(v1, 1, n), repmat(v2, m, 1))
+end
+
+function ndgrid_fill(a, v, s, snext)
+ for j = 1:length(a)
+ a[j] = v[div(rem(j-1, snext), s)+1]
+ end
+end
+
+function ndgrid{T}(vs::AbstractVector{T}...)
+ n = length(vs)
+ sz = map(length, vs)
+ out = ntuple(i->Array(T, sz), n)
+ s = 1
+ for i=1:n
+ a = out[i]::Array
+ v = vs[i]
+ snext = s*size(a,i)
+ ndgrid_fill(a, v, s, snext)
+ s = snext
+ end
+ out
+end
+
+meshgrid(v::AbstractVector) = meshgrid(v, v)
+
+function meshgrid{T}(vx::AbstractVector{T}, vy::AbstractVector{T})
+ m, n = length(vy), length(vx)
+ vx = reshape(vx, 1, n)
+ vy = reshape(vy, m, 1)
+ (repmat(vx, m, 1), repmat(vy, 1, n))
+end
+
+function meshgrid{T}(vx::AbstractVector{T}, vy::AbstractVector{T},
+ vz::AbstractVector{T})
+ m, n, o = length(vy), length(vx), length(vz)
+ vx = reshape(vx, 1, n, 1)
+ vy = reshape(vy, m, 1, 1)
+ vz = reshape(vz, 1, 1, o)
+ om = ones(Int, m)
+ on = ones(Int, n)
+ oo = ones(Int, o)
+ (vx[om, :, oo], vy[:, on, oo], vz[om, on, :])
+end