スティーブの答えは、**演算子に依存したい場合はうまくいくはずです。しかし、その演算子が正式にサポートされておらず、その解がOPの質問に直接答えるわけではないので、ここでは象徴的表現の指数を拡張できる関数があります。
function [ text ] = remove_powers(exp)
%Cleans the powers from T, and return expanded text representation
% Define functions
enclose [email protected](t) ['(' t ')'];
[email protected](b,p) strjoin(strcat(cell(1,p),enclose(char(b))),'*');
[email protected](s) arrayfun(@(k) count(char(s(k)),'^'), 1:length(s));
sym2str = @(s) strrep(char(s), ' ', '');
% Check for fractions
[N,D]=numden(exp);
if ~isequal(D,sym(1))
% pass up the num and den
text = [remove_powers(N) '/' enclose(remove_powers(D))];
else
% Split a into subterms
Ts = children(exp);
% Clean children
has_pow=count_pow(Ts)>0;
text = sym2str(exp);
if sum(count_pow(Ts))<count_pow(exp)
% We have removed a power, clean it, expand it, and pass up
text = expand_pow(remove_powers(Ts(1)),Ts(2));
else
% Just clean the unclean children and pass up
for t=Ts(has_pow)
text = strrep(text,sym2str(t),remove_powers(t));
end
end
end
end
関数が再帰的に各部分式をきれいにし、親に(テキストとして)それを置き換えるためにMATLABでchildren
機能を使用しています。このメソッドは、正規表現を使用するよりも優れています。なぜなら、スティーブがcos(x^2+2*y)^2
に関するコメントで述べたように、構文解析の問題を回避するからです。良い例になり
:
syms x y real
exp = cos(x^2+2*y)^2;
cleaned_exp = remove_powers(exp)
出力:MATLABは、解析を行っていることから、「^」演算子の優先順位を解析する必要がなかったことを(cos(2*y+(x)*(x)))*(cos(2*y+(x)*(x)))
お知らせこれは正規表現で達成するのが難しいかもしれません。 OPの例をテストするには
:予想通り
syms ddth1t dth1t th1t ddth2t dth2t th2t w11 w12 w13 J11 J31 real
exp = (J31*(2*ddth2t*cos(th1t) - 2*w12*w13 - 4*dth1t*dth2t*sin(th1t) - 4*dth2t*w13*sin(th1t) + dth1t^2*sin(2*th2t)*cos(th1t) - w12^2*sin(2*th2t)*cos(th1t) + w13^2*sin(2*th2t)*cos(th1t) + 2*dth2t*w11*sin(2*th2t) + 2*w12*w13*cos(th2t)^2 + ddth1t*sin(2*th2t)*sin(th1t) + 4*dth1t*dth2t*cos(th2t)^2*sin(th1t) + 2*dth1t*w13*sin(2*th2t)*cos(th1t) + 4*dth2t*w13*cos(th2t)^2*sin(th1t) + w11*w12*sin(2*th2t)*sin(th1t) + 4*dth1t*w12*cos(th1t)^2*cos(th2t)^2 - 2*dth1t*w11*sin(2*th1t)*cos(th2t)^2 - 2*dth2t*w11*sin(2*th2t)*cos(th1t)^2 + 2*w12*w13*cos(th1t)^2*cos(th2t)^2 - w11*w13*sin(2*th1t)*cos(th2t)^2 - 4*dth2t*w12*cos(th1t)*cos(th2t)*sin(th1t)*sin(th2t)))/(2*(J11 + J31));
cleaned_exp = remove_powers(exp);
isequal(sym(cleaned_exp),exp) % This should be 1
count(cleaned_exp,'^') % This should be 0
を、新しい表現は、元と同じですが、ない「^」記号を持っていません。
'' 'を検出するための[' regexp'](http://mathworks.com/help/matlab/ref/regexp.html)を書き、その前の式をそれの後ろの力で何度も代用します。 (私は正規表現できないので、そこにお手伝いすることはできません)。 – Adriaan
@Adriaanが動作する可能性があります。私は正規表現では得られないので、おそらく私がハードコードを変更するのがテキストエディタである方が速いでしょう。 –
'syms th2t;' 'factor(cos(th2t)^ 2)' –