0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ユークリッド距離と角度の計算

Posted at

ユークリッド距離を計算

覚書。
各点があり、重心を計算する。
重心から各点へのユークリッド距離と角度を計算する。
角度は基準として最初の点から見た角度とする。

以下、もし最初の点が重心とピタリ重なる場合、角度は計算されず(基準ベクトルが0)、全て0を返す。

import numpy as np
# 高次元データ(N個のD次元ベクトル)
data = np.array([
    [1.0, 3.0, 3.0],
    [2.0, 1.0, 4.0],
    [0.0, 3.0, 2.0]
])

# ステップ1: 重心(平均ベクトル)を計算
centroid = np.mean(data, axis=0)

# ステップ2: 各点から重心へのベクトルを計算
vectors = data - centroid

# ステップ3: 距離を計算(ユークリッド距離)
distances = np.linalg.norm(vectors, axis=1)

# ステップ4: 単位ベクトル(方向)も取得したい場合
unit_vectors = vectors / distances[:, np.newaxis]

# オプション: 角度を取りたい場合(基準方向が必要)
# ここでは例として、最初の点を基準に他との角度を計算してみます
reference = vectors[0]
angles = []
for v in vectors:
    cos_theta = np.dot(reference, v) / (np.linalg.norm(reference) * np.linalg.norm(v))
    angle = np.arccos(np.clip(cos_theta, -1.0, 1.0))  # ラジアン
    angles.append(np.degrees(angle))  # 度数法に変換

# 結果の表示
print("重心:\n", centroid)
print("各点から重心へのベクトル:\n", vectors)
print("距離:\n", distances)
print("単位ベクトル:\n", unit_vectors)
print("角度(基準は1つ目):\n", angles)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?