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

6 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 8 Apr 2015
Edited: Stephen23 on 8 Apr 2015
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.
  2 Comments
Stephen23
Stephen23 on 8 Apr 2015
Edited: Stephen23 on 8 Apr 2015
What do you mean by "opt out the diagonal matrix"? If you want the same shape as tril, then try this:
>> N = 5;
>> K = 0; % select the diagonal
>> A = 1:N;
>> B = rot90(bsxfun(@plus,A,A(:)))-1;
>> X = rand(N)
X =
0.7577 0.7060 0.8235 0.4387 0.4898
0.7431 0.0318 0.6948 0.3816 0.4456
0.3922 0.2769 0.3171 0.7655 0.6463
0.6555 0.0462 0.9502 0.7952 0.7094
0.1712 0.0971 0.0344 0.1869 0.7547
>> X(B>N+K) = 0
X =
0.7577 0 0 0 0
0.7431 0.0318 0 0 0
0.3922 0.2769 0.3171 0 0
0.6555 0.0462 0.9502 0.7952 0
0.1712 0.0971 0.0344 0.1869 0.7547
And of course if you don't want to change the variable X then simply allocate it to another variable and change that one instead..

Sign in to comment.

More Answers (1)

Jos (10584)
Jos (10584) on 8 Apr 2015
A = rand(5) ; %
[c,r] = meshgrid(1:size(A,1),1:size(A,2))
trilA = A ;
trilA(c>r) = 0
diagA = A ;
diagA(c ~= r) = 0

Categories

Find more on Linear Algebra in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!