Rectangular matrix manipulation with triu and tril

조회 수: 8 (최근 30일)
Pranav Murali
Pranav Murali 2020년 7월 19일
편집: John D'Errico 2020년 7월 19일
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

답변 (2개)

John D'Errico
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.

the cyclist
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))

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by