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

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

 採用された回答

Stephen23
Stephen23 2015 年 4 月 8 日
編集済み: Stephen23 2015 年 4 月 8 日
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 件のコメント

ali92
ali92 2015 年 4 月 8 日
Thanks for the answer. How would you opt out the diagonal matrix from your list of outputs though?
Stephen23
Stephen23 2015 年 4 月 8 日
編集済み: Stephen23 2015 年 4 月 8 日
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..

サインインしてコメントする。

その他の回答 (1 件)

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

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

質問済み:

2015 年 4 月 8 日

編集済み:

2015 年 4 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by