2014-12-02 54 views
1

我可以將產品產品符號轉換爲產品數組嗎?將matlab符號轉換爲產品數組

我試圖做這樣的事情:

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

但並不因素出來(主要是因爲這不是什麼因素是專門做)。

ans = 
A*B*C 

我需要它來工作,如果A B或C被替換爲任何任意複雜的括號的功能,這將是很好做的不知道是在什麼樣的功能變量。

例如(所有變量都是象徵性的):

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

應該是: [x, x-1, (cos(z) + n)]

這似乎是一個字符串解析的問題,但我不相信,我可以轉換回符號之後的變量(另外,在matlab中的字符串解析聽起來很乏味)。

謝謝!

+1

您使用的是什麼'版本'的Matlab?在R2014b中,'因素(A * B * C)'返回'[A,B,C]'。另一個例子也很好。還是試圖爲作業編寫自己的版本? – horchler 2014-12-02 02:41:58

+0

我在2013b。這不是一項任務,而是一項研究項目。我實際上找到了一個可以完成「孩子」這個工作的功能。我仍在測試它以確保它沒有任何角落案例(我不希望它通過總和,只有產品分割) – Chet 2014-12-02 03:18:04

+1

我無法測試版本之間是否存在差異,但我不會如果有的話會感到驚訝。也許你也可以嘗試使用'sym/factor'的第二個參數。你也可能會發現'symvar'有幫助。如果您找到解決方案,請隨時回答您自己的問題 - 只需指定您使用的是哪個Matlab版本。 – horchler 2014-12-02 03:36:22

回答

0

在字符串中使用regexp來分割基於*

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

結果​​是字符串的單元陣列。要轉換到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 
+0

不是我最終做的,但可能是一個更適合那些誰來這裏尋找matlab代碼的答案。 – Chet 2014-12-03 07:32:30

0

我最後寫的代碼使用sympy做到這一點的蟒蛇。我想我將把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) 
相關問題