MATLAB: How to avoid for loops when generating index arrays

for loopindexingloopMATLABvectorization

I often find myself coding nested for loops to generate vectors of integer indices. For example:
n = 4;
i = 1;
for L = 0:n
for M = -L:L
l(i) = L;
m(i) = M;
i = i+1;
end
end
All I need are the vectors "l" and "m". I can preallocate to save some speed, but my real problem is having to use the for loops as sometimes the index vectors I need to create have many more nested for loops whose (note that the inner loop index depends on the outer loop index).
Is there a simple way to avoid using loops to generate index vectors like these?

Best Answer

Here's another method, less memory consuming than NDGRID
mm=sparse(-n:n);
ll=sparse(0:n);
map=bsxfun(@le,abs(mm.'),ll);
idx=nonzeros(bsxfun(@times,map,1:length(ll) ));
l=full(ll(idx));
idx=nonzeros(bsxfun(@times,map,(1:length(mm)).')) ;
m=full(mm(idx));