Q:

Matlab, Polygonal numbers

I was working about polygonal numbers and doing a list of what numbers can be represented as a sum of three 27-gonals.  I have done a Matlab code but it is really slow.  Can you please help me to improve it? 
    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

Thanks

A:

You can do the whole thing with the following (I think):
n = 0:100;
pn = (25*n.^2 - 23*n)/2;

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

The function bsxfun is really helpful in MATLAB for vectorized operations like this.  You can read the documentation here.  Basically bsxfun gives you an efficient way of performing element-wise binary operations between two vectors. 
The first expression using bsxfun in the above adds every value of pn' to every value of pn and creates a matrix of the results.  By using the unique function, you only store unique values from this matrix.  The second expression using bsxfun then adds every value of pn to this vector of unique results from the first expression.  The result should be a vector of all unique combinations of pn(n) + pn(m) + pn(l). 
In general, in MATLAB, using built in vectorization functions is a lot faster than using loops.  This is counterintuitive if you have done much programming in C++ and the like, but it is because MATLAB is an interpreted language and basically using the built in vectorized functions results in more efficient actual code that is executed on the processor.  Weird as it is, you want to avoid loops in MATLAB.