How to vectorize double dependence loop in Matlab?

67 Views Asked by At

I have a loop function which the inner loop depends on the value of your outer loop.

for jj = 1:500
     for ii = jj:500
         Gamma(ii,jj) =mod( ii-jj, 255);
     end
end

I am looking for the way to make the code is fastest: vectorized or bsxfun. Now, I am using vectorized way but it may not optimal. I ask the question to find a better solution or at least better than my way.

[iiValues, jjValues] = meshgrid(1:500, 1:500); 
mask = iiValues >= jjValues;  % ii >= jj
ii= iiValues(mask);    
jj= jjValues(mask);
Gamma(ii,jj)=mod(ii-jj,255) % I am not sure about the line

Thanks

1

There are 1 best solutions below

0
Sardar Usama On BEST ANSWER

Using bsxfun and tril:

Gamma = mod(tril(bsxfun(@minus, (1:500).', 1:500)), 255);
%this 1:500 is for the inner loop---^        ^---This 1:500 is for the outer loop

or using the same approach with implicit expansion (for MATLAB R2016b and later):

Gamma = mod(tril((1:500).'-(1:500)), 255);