算法程序代码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

多项式求值和矩阵乘法

1.用MATLAB实现多项式求值的四种运算,针对不同规模的输入值,绘制四种算法时间的比较图

num=[10 50 100 150 200 300 400 500 10000 20000 50000 100000];

x=input('please enter x:')

for m=1:12

a=rand(1,num(m)+1);

tic;

p1(m)=polyval(a,x);

t1(m)=toc;

tic;

p2(m)=0;

for i=1:num(m)+1

p2(m)=p2(m)+a(i)*x^(i-1);

t2(m)=toc;

end

tic;

p3(m)=a(1);

q=1;

for j=2:num(m)+1

q=q*x;

p3(m)=p3(m)+a(j)*q;

t3(m)=toc;

end

tic;

p4(m)=a(num(m)+1);

for k=1:num(m);

p4(m)=x*p4(m)+a(num(m)+1-k);

t4(m)=toc;

end

end

semilogx(num,t1,'b+',num,t2,'gx',num,t3,'r*',num,t4,'ko');

xlabel('num=10,50,100,150,200,300,400,500,10000,20000,50000,100000' ); ylabel('time');

title('The comparison chart of four different methods for polyval')

2.用MATLAB实现矩阵乘法的三种算法,并比较不同规模时的运行时间

num=[2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10,2^11]

for m=1:10

A=round(rand(num(m)));

B=round(rand(num(m)));

tic;

C1=A*B;

t1(m)=toc;

tic;

C2=zeros(num(m));

for i=1:num(m)

for k=1:num(m)

for j=1:num(m)

C2(i,j)=C2(i,j)+A(i,k)*B(k,j);

end

end

end

t2(m)=toc;

A11=A(1:num(m)/2,1:num(m)/2);

A12=A(1:num(m)/2,num(m)/2+1:num(m));

A21=A(num(m)/2+1:num(m),1:num(m)/2);

A22=A(num(m)/2+1:num(m),num(m)/2+1:num(m));

B11=B(1:num(m)/2,1:num(m)/2);

B12=B(1:num(m)/2,num(m)/2+1:num(m));

B21=B(num(m)/2+1:num(m),1:num(m)/2);

B22=B(num(m)/2+1:num(m),num(m)/2+1:num(m));

tic;

C3=zeros(num(m));

C11=A11*B11+A12*B21;

C12=A11*B12+A12*B22;

C21=A21*B11+A22*B21;

C22=A21*B12+A22*B22;

C3=[C11 C12;C21 C22];

t3(m)=toc;

tic;

C4=zeros(num(m));

M1=A11*(B12-B22);

M2=(A11+A12)*B22;

M3=(A21+A22)*B11;

M4=A22*(B21-B11);

M5=(A11+A22)*(B11+B22);

M6=(A12-A22)*(B21+B22);

M7=(A11-A21)*(B11+B12);

C11=M5+M4-M2+M6;

C12=M1+M2;

C21=M3+M4;

C22=M5+M1-M3-M7;

C4=[C11 C12;C21 C22];

t4(m)=toc;

end

plot(log(num)/log(2),t1,'b+',log(num)/log(2),t2,'gx',log(num)/log(2),t3,'r*',log(num)/log(2),t4,'ko'); xlabel('log(num)/log(2)=2^2,2^3,2^4,2^5,2^6,2^8,2^9,2^1^0,2^1^1' );

ylabel('time');

title('The comparison chart of four different methods for matrix multiplication')

三、遗传算法代码

%%%*****用遗传算法求函数最大值(双变量单输出)****%%%%%

clc;

clear;

x1min=-3.0; %输入变量1的变化范围

x1max=12.1;

x2min=4.1; %输入变量2的变化范围

x2max=5.8;

pb=0.001; %变异概率

N=300; %初始种群数目=300

s1=ceil(log2(100000*(x1max-x1min))); %计算二进制串的长度

s2=ceil(log2(100000*(x2max-x2min))); %精确到小数点后面5位

s=s1+s2; %%种群的位数

zq=randi(N,s); %产生初始种群,for循环

for i=1:N

for j=1:s

r=rand(1);

if r>0.5

zq(i,j)=1;

else zq(i,j)=0;

end

end

end

%%*****用于二进制转化为十进制****

for i=1:s1

zhuanhuan(i,1) = 2^(s1-i);

end

for i=s1+1:s

zhuanhuan(i,1) = 2^(s-i);

end

for k=1:1000 %遗传算法的次数

%%********将二进制转换成十进制

相关文档
最新文档