Modified FOR loop for speed...
N = 5;
X = false(N);
for ii = 1:N
X(ii,a(ii):b(ii)) = 1;
end
X = double(X);
Note that if logicals will work for your application, then the last line is not needed.
%
%
%
EDIT In response to your extra request for a vectorized solution.
X2 = zeros(N,N);
C = b-a+1;
R = zeros(1,sum(C));
R([0;cumsum(C(1:N-1))]+1) = 1;
C = arrayfun(@colon,a,b,'un',0);
C = [C{:}];
X2(cumsum(R)+(C-1)*N) = 1;
MCOLON might speed up the call to ARRAYfUN. Using ARRAYFUN as above, this is much slower than the FOR loop for 5000-by-5000 X (N=5000), and occasionally runs out of memory. I tested the above using: N = 5000;
a = ceil(rand(N,1)*N);
b = min(a+round(rand(N,1)*N),N);
Best Answer