1

積の積であるシンボルを積の配列に変換できますか?

私はこのようなことをしようとしました:

syms A B C D;
D = A*B*C;
factor(D);

しかし、それはそれを除外しません (主に、それが factor が行うように設計されているものではないためです)。

ans =
A*B*C

AB または C が任意に複雑な括弧で囲まれた関数に置き換えられた場合に機能する必要があり、関数に含まれる変数を知らなくてもそれを行うとよいでしょう。

例 (すべての変数はシンボリックです):

D = x*(x-1)*(cos(z) + n);
factoring_function(D);

次のようにする必要があります。 [x, x-1, (cos(z) + n)]

文字列解析の問題のようですが、後でシンボリック変数に変換できるかどうか自信がありません (また、matlab での文字列解析は非常に面倒に思えます)。

ありがとうございました!

4

2 に答える 2

0

私はsympyを使ってpythonでこれを行うコードを書くことになりました。python は私にとってより好ましい言語であるため、matlab コードを python に移植するつもりだと思います。これが速いと主張しているわけではありませんが、私の目的には役立ちます。

# Factors a sum of products function that is first order with respect to all symbolic variables
# into a reduced form using products of sums whenever possible.
# @params orig_exp     A symbolic expression to be simplified
# @params depth        Used to control indenting for printing
# @params verbose      Whether to print or not
def factored(orig_exp, depth = 0, verbose = False):
  # Prevents sympy from doing any additional factoring
  exp = expand(orig_exp)
  if verbose: tabs = '\t'*depth
  terms = []

  # Break up the added terms
  while(exp != 0):
    my_atoms = symvar(exp)
    if verbose: 
      print tabs,"The expression is",exp
      print tabs,my_atoms, len(my_atoms)

    # There is nothing to sort out, only one term left
    if len(my_atoms) <= 1:
      terms.append((exp, 1))
      break

    (c,v) = collect_terms(exp, my_atoms[0])
    # Makes sure it doesn't factor anything extra out
    exp = expand(c[1])
    if verbose: 
      print tabs, "Collecting", my_atoms[0], "terms."
      print tabs,'Seperated terms with ',v[0], ',  (',c[0],')'

    # Factor the leftovers and recombine
    c[0] = factored(c[0], depth + 1)
    terms.append((v[0], c[0]))


  # Combines trivial terms whenever possible
  i=0
  def termParser(thing): return str(thing[1])
  terms = sorted(terms, key = termParser) 

  while i<len(terms)-1:
    if equals(terms[i][1], terms[i+1][1]):
      terms[i] = (terms[i][0]+terms[i+1][0], terms[i][1])
      del terms[i+1]
    else:
      i += 1

  recombine = sum([terms[i][0]*terms[i][1] for i in range(len(terms))])
  return simplify(recombine, ratio = 1)
于 2014-12-03T07:31:25.887 に答える
0

regexpに基づいて分割する文字列で使用し*ます。

>> str = 'x*(x-1)*(cos(z) + n)';
>> factors_str = regexp(str, '\*', 'split')
factors_str = 
    'x'    '(x-1)'    '(cos(z) + n)'

結果factor_strは、文字列のセル配列です。symオブジェクトのセル配列に変換するには、次を使用します。

N = numel(factors_str);
factors = cell(1,N); %// each cell will hold a sym factor
for n = 1:N
    factors{n} = sym(factors_str{n});
end
于 2014-12-02T11:48:47.377 に答える