2013-07-01 58 views
1

我当时在做关于多边形数的工作,并且列出了可以表示为三个27-gonals之和的数字。我做了一个Matlab代码,但它确实很慢。你能帮我改进吗?Matlab,多边形数

n=0:100;    % number of polygonals 
    pn=(25*n.^2-23*n)/2; % vector of 27-gonal numbers 
    s=1; 
    % the following part generate the list of numbers represented as a sum of three 27- gonals 
    for n=1:101 
     for m=1:101 
      for l=1:101 
       sumadetres(s)=pn(n)+pn(m)+pn(l); 
       s=s+1; 
      end 
     end 
    end 
    k=1; 

    % some of the numbers are repeted, so the following part eliminated the repeated ones. 
    n=length(sumadetres); 

    while k<=n 
     j=1; 
     while j<=n 
      if k~=j 
       if sumadetres(k)==sumadetres(j) 
        sumadetres(j)=[]; 
        n=length(sumadetres); 
       end 
      end 
      j=j+1; 
     end 
     k=k+1; 
    end 

    sumadetres=sort(sumadetres); % organise the numbers 

感谢

回答

4

你可以做整个事情有以下(我认为):

n = 0:100; 
pn = (25*n.^2 - 23*n)/2; 

sumadetres = unique(bsxfun(@plus, pn, pn')); 
sumadetres = unique(bsxfun(@plus, sumadetres, pn)); 

功能bsxfun是在MATLAB像这样量化的操作非常有帮助。你可以阅读the documentation here。基本上bsxfun为您提供了一种在两个向量之间执行基于元素的二进制操作的有效方法。

上述第一个使用bsxfun的表达式将pn'的每个值都添加到每个值pn并创建结果矩阵。通过使用unique函数,您只能存储此矩阵中的唯一值。然后使用bsxfun的第二个表达式将pn的每个值添加到来自第一个表达式的唯一结果的此向量中。结果应该是pn(n) + pn(m) + pn(l)的所有独特组合的向量。

一般来说,在MATLAB中,使用内置的矢量化函数比使用循环要快得多。如果你用C++等进行了大量编程,这是违反直觉的,但是这是因为MATLAB是一种解释型语言,基本上使用内置的向量化函数会导致在处理器上执行更高效的实际代码。奇怪的是,你想避免MATLAB中的循环。