MATLAB: Hi, guys. How would one extract the lower triangle of a matrix without using the tril function and witout a for loop

bsxfunlower trianglematrix manipulationrot90triangletril

I tried
B = zeros(size(A)); n=size(A,2);
for(i=1:n) B(end+1:end+n-i+1)=A(i:n,i); end
but I seem to be getting some sort of error.
Thanks

Best Answer

You could use bsxfun and rot90 to generate a matrix of indices:
>> N = 5;
>> K = 0; % select the diagonal
>> 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.
Related Question