2013-07-01 57 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中的循環。