Rectangular matrix manipulation with triu and tril

7 visualizaciones (últimos 30 días)
Pranav Murali
Pranav Murali el 19 de Jul. de 2020
Editada: John D'Errico el 19 de Jul. de 2020
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

Respuestas (2)

John D'Errico
John D'Errico el 19 de Jul. de 2020
Editada: John D'Errico el 19 de Jul. de 2020
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 el 19 de Jul. de 2020
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))

Categorías

Más información sobre Linear Algebra en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by