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のユーザー定義関数「(applyfunc)sympy の Matrix([[P**2-Q**2, 2*P-2*Q],[2*Q-2*R,R**2-P**2] ]) の全要素をfactorする方法を教えて下さい。」をAI先生ヘ。

Posted at

・applyfunc(f)
Apply a function to each element of the matrix.

(本日の)ChatGPT先生へ

# 質問リスト
1. sympy の Matrix([[P**2-Q**2, 2*P-2*Q],[2*Q-2*R,R**2-P**2] ]) の全要素をfactorする方法を教えて下さい。
2. applyfunc を 使って 2倍にしてほしい。
3. applyfunc の引数にユーザー定義関数も扱えますか
4. 複数処理を教えて下さい。
5. 私の質問をMarkdown形式でリスト化して出力して。Markdown形式でリストからアスタリスクは削除して。1行目に、# 質問リスト の文字を出力して。最後の質問も追加して下さい。追番を追加して下さい。

(以下回答抜粋)

sympy において、行列の全要素を factor したい場合は、行列全体に対して applyfunc(factor) を使います。applyfunc は各要素に任意の関数を適用するメソッドです。

from sympy import symbols, Matrix, factor

# 記号の定義
P, Q, R = symbols('P Q R')

# 行列の定義
M = Matrix([[P**2 - Q**2, 2*P - 2*Q],
            [2*Q - 2*R, R**2 - P**2]])

# 各要素に factor を適用
factored_M = M.applyfunc(factor)

# 結果表示
print(factored_M)

もちろんです!Matrix.applyfunc を使えば、各要素を2倍にすることも簡単にできます。たとえば、元の行列の各要素を2倍するには、次のようにします:

from sympy import symbols, Matrix

# 記号の定義
P, Q, R = symbols('P Q R')

# 元の行列
M = Matrix([[P**2 - Q**2, 2*P - 2*Q],
            [2*Q - 2*R, R**2 - P**2]])

# 各要素を2倍
doubled_M = M.applyfunc(lambda x: 2 * x)

# 結果表示
print(doubled_M)

はい、applyfunc の引数には ユーザー定義関数 も問題なく使えます。
lambda ではなく通常の def で定義した関数でもOKです。

from sympy import symbols, Matrix, factor

# 記号の定義
P, Q, R = symbols('P Q R')

# 行列の定義
M = Matrix([[P**2 - Q**2, 2*P - 2*Q],
            [2*Q - 2*R, R**2 - P**2]])

# ユーザー定義関数
def my_transform(expr):
    return 2 * factor(expr)

# applyfunc に渡す
M_transformed = M.applyfunc(my_transform)

# 結果表示
print(M_transformed)

🔧 例:以下の3つの処理を行う関数

from sympy import symbols, Matrix, expand, factor

# 記号の定義
P, Q, R = symbols('P Q R')

# 行列の定義
M = Matrix([[P**2 - Q**2, 2*P - 2*Q],
            [2*Q - 2*R, R**2 - P**2]])

# 複数処理を行う関数
def multi_transform(expr):
    expanded = expand(expr)       # 必要なら展開
    factored = factor(expanded)   # 因数分解
    doubled = 2 * factored        # 2倍
    return doubled

# applyfunc に適用
M_processed = M.applyfunc(multi_transform)

# 結果表示
print(M_processed)

Gemini先生へ

copilot先生へ

いつもの? sympyの実行環境と 参考のおすすめです。

(テンプレート)

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

Qiita内

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?