matlab求解多项式系数,matlab如何提取多项式的系数???

下面提供比贴在17楼更高效的

多项式系数提取函数。

最大不同就是新版本不再使用变量temp

==================================================

function [c,t]= poly_coeffs_new(fcn,var)

% 输入:

%      fcn 为待确定系数值多项式的符号表达式

%      var 为多项式的主变量,如果是单变量可省略之。

% 输出:

%      c 为多项式系数向量,输出变量为两个时(即[c,t]),c向量分量从左到右所对应的变量幂次由高到低。

%                    输出变量(只有c或没有时), c向量分量从左到右所对应的变量幂次由低到高。

%      t 与系数向量相对应项的变量向量,即 fcn=c*conj(t)'

var0=findsym(fcn);

if nargin<2;

var=var0;

lvar=length(var0);

else

if ismember(abs(char(var)),abs(char(var0)))

lvar=1;        %%% 'var' is included in  'fcn'

else

lvar=0;        %%% 'var' is not included in 'fcn'

end

end

switch lvar

case 0

c=fcn;

t=sym(1);

case 1

[c0,t0]=coeffs(fcn,var);

pwr=log2(subs(t0,2));

m=pwr(1);

c=sym(zeros(1,m+1));

if nargout==2

c(m+1-pwr)=c0;

t=sym(char(var)).^(m:-1:0);         %%% If t=var.^(m:-1:0), it does not work.

else

c(pwr+1)=c0;

end

otherwise

error('Specify var please.');

end

====================================================

下面是新旧版本运行时间比较实验。

每次测试实验分别重复执行多项式系数提取函数100次。

test 比较新旧版本执行效率的测试函数,在附件中。

新版本可节省近一半的运行时间。

>> syms x y

>> f3 =x^5 + 2*x^3*y^4 + x*y^2 + 4

f3 =

x^5 + 2*x^3*y^4 + x*y^2 + 4

[c1,c2,t1,t2] = test(f3,x)

Elapsed time is 10.1461 seconds for poly_coeffs_new.

Elapsed time is 17.7343 seconds for poly_coeffs_new.

c1 =

[ 1, 0, 2*y^4, 0, y^2, 4]

c2 =

[ 1, 0, 2*y^4, 0, y^2, 4]

t1 =

[ x^5, x^4, x^3, x^2, x, 1]

t2 =

[ x^5, x^4, x^3, x^2, x, 1]

>> [c1,c2,t1,t2] = test(f3,x)

Elapsed time is 9.4647 seconds for poly_coeffs_new.

Elapsed time is 16.0407 seconds for poly_coeffs_new.

c1 =

[ 1, 0, 2*y^4, 0, y^2, 4]

c2 =

[ 1, 0, 2*y^4, 0, y^2, 4]

t1 =

[ x^5, x^4, x^3, x^2, x, 1]

t2 =

[ x^5, x^4, x^3, x^2, x, 1]

>> [c1,c2,t1,t2] = test(f3,x)

Elapsed time is 9.5414 seconds for poly_coeffs_new.

Elapsed time is 16.252 seconds for poly_coeffs (old version).

c1 =

[ 1, 0, 2*y^4, 0, y^2, 4]

c2 =

[ 1, 0, 2*y^4, 0, y^2, 4]

t1 =

[ x^5, x^4, x^3, x^2, x, 1]

t2 =

[ x^5, x^4, x^3, x^2, x, 1]

>> [c1,c2,t1,t2] = test(f3,x)

>> [c1,c2,t1,t2] = test(f3,y)

Elapsed time is 8.0488 seconds for poly_coeffs_new.

Elapsed time is 13.8489 seconds for poly_coeffs (old version).

c1 =

[ 2*x^3, 0, x, 0, x^5 + 4]

c2 =

[ 2*x^3, 0, x, 0, x^5 + 4]

t1 =

[ y^4, y^3, y^2, y, 1]

t2 =

[ y^4, y^3, y^2, y, 1]

>> [c1,c2] = test(f3,y)

Elapsed time is 6.2817 seconds for poly_coeffs_new.

Elapsed time is 12.4151 seconds for poly_coeffs (old version).

c1 =

[ x^5 + 4, 0, x, 0, 2*x^3]

c2 =

[ x^5 + 4, 0, x, 0, 2*x^3]

>> [c1,c2] = test(f3,x)

Elapsed time is 7.6425 seconds for poly_coeffs_new.

Elapsed time is 14.7012 seconds for poly_coeffs (old version).

c1 =

[ 4, y^2, 0, 2*y^4, 0, 1]

c2 =

[ 4, y^2, 0, 2*y^4, 0, 1]

===========================================

附件:1.新版本m文件

2.比较新旧版本执行效率的测试函数之m文件

你可能感兴趣的:(matlab求解多项式系数)