Skip to content

Instantly share code, notes, and snippets.

@KatsuhiroMorishita
Last active February 19, 2017 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatsuhiroMorishita/16a2da253a8afbf60ec83a721309dcac to your computer and use it in GitHub Desktop.
Save KatsuhiroMorishita/16a2da253a8afbf60ec83a721309dcac to your computer and use it in GitHub Desktop.
VBAで実装したベクトルの関数群です。基本的な計算なら対応しています。足し算、引き算、スカラー倍、内積、外積、ノルム、正規化です。
Function vector_plus(vect1, vect2)
' ベクトルの足し算
ans = vect1 ' deep copy (たぶん、ディープコピー)
For i = 0 To UBound(ans)
ans(i) = vect1(i) + vect2(i)
Next i
vector_plus = ans
End Function
Function vector_minus(vect1, vect2)
' ベクトルの引き算
ans = vect1 ' deep copy
For i = 0 To UBound(ans)
ans(i) = vect1(i) - vect2(i)
Next i
vector_minus = ans
End Function
Function vector_times(vect, coefficient)
' ベクトルに定数を掛ける
ans = vect ' deep copy
For i = 0 To UBound(vect)
ans(i) = coefficient * vect(i)
Next i
vector_times = ans
End Function
Function vector_inner(vect1, vect2)
' ベクトルの内積
ans = 0
For i = 0 To UBound(vect1)
ans = ans + vect1(i) * vect2(i)
Next i
vector_inner = ans
End Function
Function vector_cross(vect1, vect2)
' ベクトルの外積
ans = vect1 ' deep copy
ans(0) = vect1(1) * vect2(2) - vect1(2) * vect2(1)
ans(1) = vect1(2) * vect2(0) - vect1(0) * vect2(2)
ans(2) = vect1(0) * vect2(1) - vect1(1) * vect2(0)
vector_cross = ans
End Function
Function vector_norm(vect)
' ベクトルのノルムを返す
v = vector_inner(vect, vect)
vector_norm = v ^ 0.5
End Function
Function vector_normalization(vect)
' ベクトルの長さを1とする(正規化する)
Length = vector_norm(vect)
vector_normalization = vector_times(vect, 1 / Length)
End Function
Sub vector_test()
' セルに表示させるテスト
Dim a() As Double
b = 100 ' bは変数
ReDim a(b) ' aの要素数がbで初期化される
a(0) = 256
Cells(1, 4) = a ' 第1要素しか表示されない
c = Range("A1:B2")
Cells(1, 6) = c
r1 = Array(11, 12, 13)
r2 = Array(21, 22, 23)
r3 = Array(31, 32, 33)
d = Array(r1, r2, r3)
Cells(1, 1) = r1
Dim e(2, 2) As Double
e(0, 0) = 100
e(0, 1) = 200
e(0, 2) = 300
e(1, 0) = 400
e(1, 1) = 500
e(1, 2) = 600
Cells(1, 1) = e
Range("a1") = e
Dim f(2) As Double
f(0) = 100
f(1) = 123
f(1) = 256
Cells(1, 1) = f
Range("a1") = f
Dim g As Variant
g = Array()
ReDim g(2)
g(0) = 100
g(1) = 654
g(2) = 758
Cells(1, 1) = g
Range("a1") = g
v1 = Array(11, 12, 13)
v2 = Array(21, 22, 23)
v3 = vector_plus(v1, v2)
v3 = vector_minus(v1, v2)
v3 = vector_times(v1, 2)
v3 = vector_inner(v1, v2)
v3 = vector_norm(v1)
v3 = vector_normalization(v1)
v1 = Array(1, 0, 0)
v2 = Array(0, 1, 0)
v3 = vector_cross(v1, v2)
v3 = vector_norm(v1)
v3 = vector_normalization(v1)
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment