1

我可以将作为产品产品的符号转换为产品数组吗?

我试图做这样的事情:

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

但它并没有把它排除在外(主要是因为这不是因素设计的目的)。

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 中编写了代码来执行此操作。我想我要把 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 回答