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?

pythonのユーザー定義関数「SymPyの行列で、位置を指定して埋め込み。」AI先生へ。

Last updated at Posted at 2025-07-14

ChatGPT先生へ

📋 本チャット内の質問一覧(Markdown形式)

1. SymPyの行列で、位置を指定して埋め込み。
2. 例1で、サイズ2が必要ですか。
3. サイズを自動入力で教えて下さい。
4. 本チャット、この会話で出てきた全ての質問を、いつもの Markdownのテキスト形式で一覧にしてください。追番も。

🔹 例1:部分行列を指定位置に埋め込む

from sympy import Matrix

# 大きなゼロ行列
M = Matrix.zeros(4, 4)

# 埋め込みたい小さな行列
A = Matrix([[1, 2], [3, 4]])

# 埋め込み(例:左上2×2に)
M[0:2, 0:2] = A

print(M)

🔹 例2:要素を個別に代入(位置を1つずつ指定)

from sympy import Matrix, symbols

x, y = symbols('x y')
M = Matrix.zeros(3, 3)

M[0, 0] = x
M[2, 1] = y

print(M)

🔹 関数としてまとめる(任意位置に埋め込む)

def embed_matrix(big, small, row, col):
    big[row:row + small.rows, col:col + small.cols] = small
    return big

# 使用例
B = Matrix.zeros(5, 5)
S = Matrix([[9, 8], [7, 6]])

B = embed_matrix(B, S, 2, 3)
print(B)
例1で、サイズ2が必要ですか。

✅ サイズ自動取得の関数:embed_matrix

from sympy import Matrix

def embed_matrix(big, small, row, col):
    """
    big: 埋め込み先の行列
    small: 埋め込む行列
    row: 開始行インデックス
    col: 開始列インデックス
    """
    r, c = small.shape  # サイズを自動取得
    big[row:row + r, col:col + c] = small
    return big

✅ 使用例:

# 5×5のゼロ行列
M = Matrix.zeros(5, 5)

# 埋め込む2×2行列
A = Matrix([[1, 2],
            [3, 4]])

# 自動的にサイズを取得して、(1,1)から埋め込む
M = embed_matrix(M, A, 1, 1)

print(M)

出力例

Matrix([[0, 0, 0, 0, 0], [0, 1, 2, 0, 0], [0, 3, 4, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
⎡0  0  0  0  0⎤
⎢             ⎥
⎢0  1  2  0  0⎥
⎢             ⎥
⎢0  3  4  0  0⎥
⎢             ⎥
⎢0  0  0  0  0⎥
⎢             ⎥
⎣0  0  0  0  0⎦

Gemini先生へ

いつもと違うおすすめです。

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?