Rectangular matrix manipulation with triu and tril
8 ビュー (過去 30 日間)
古いコメントを表示
Hey guys,
I am currently working with matrices that have several different sizes such as 256x153, 303x106, 127x89, and many more. Whenever I use a perfect square matrix, the cut made by the triu and tril commands are from the top left corner of the matrix to the bottom right corner; however, when I use a rectangular matrix this is not the case. Is there a line of code that I can implement so that the cut made by tril and triu ALWAYS cuts a matrix of ANY SIZE through the bottom right corner?
Thanks,
Pranav
0 件のコメント
回答 (2 件)
John D'Errico
2020 年 7 月 19 日
編集済み: John D'Errico
2020 年 7 月 19 日
tril and triu are set so they work from the top left corner. You don't want them to work that way. So you could write your own version of the codes, to just then use tril and triu with a tweak to the diagonal chosen.
The fix is pretty simple.
function Ahat = trilb(A,K)
% like tril, but it acts relative to the lower right corner of the matrix
if (nargin <2) || isempty(K)
K = 0;
end
da = diff(size(A));
Ahat = tril(A,K + da);
end
function Ahat = triub(A,K)
% like triu, but it acts relative to the lower right corner of the matrix
if (nargin <2) || isempty(K)
K = 0;
end
da = diff(size(A));
Ahat = triu(A,K + da);
end
Do they work? So it would seem.
triu(ones(3,5))
ans =
1 1 1 1 1
0 1 1 1 1
0 0 1 1 1
>> triub(ones(3,5))
ans =
0 0 1 1 1
0 0 0 1 1
0 0 0 0 1
>> tril(ones(3,5))
ans =
1 0 0 0 0
1 1 0 0 0
1 1 1 0 0
>> trilb(ones(3,5))
ans =
1 1 1 0 0
1 1 1 1 0
1 1 1 1 1
Effectively, it could be thought of as a one line fix, but easier if you just write the functions to do it for you. Otherwise, you would need to remember whether to add or subtract the difference in dimension from K. And clearly, the result is no different from tril and triu when the matrix is square.
0 件のコメント
the cyclist
2020 年 7 月 19 日
This will use the largest square matrix from the bottom right corner, as input to triu:
d = min(size(A))-1;
triu(A(end-d:end,end-d:end))
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!