You could use bsxfun and rot90 to generate a matrix of indices: >> N = 5;
>> K = 0;
>> A = 1:N;
>> B = rot90(bsxfun(@plus,A,A(:)))-1;
Now lets try it on matrix of random values and extract only the lower diagonal elements:
>> X = rand(N);
>> X(B<=N+K)
ans =
0.81472
0.90579
0.12699
0.91338
0.63236
0.2785
0.54688
0.95751
0.96489
0.95717
0.48538
0.80028
0.79221
0.95949
0.67874
And you can see that it extracts all of the lower-triangle values, matching those given by tril:
>> tril(X)
ans =
0.81472 0 0 0 0
0.90579 0.2785 0 0 0
0.12699 0.54688 0.95717 0 0
0.91338 0.95751 0.48538 0.79221 0
0.63236 0.96489 0.80028 0.95949 0.67874
Note that this method also gives direct control over which diagonal you start with using the value K, just like the second argument of tril.
Best Answer