去掉对称矩阵的上三角或下三角部分

getting rid of the upper or lower triangular part of a symmetric matrix

我有一些统计值的对称矩阵,我想在 Matlab 中使用 imagesc 绘制这些值。矩阵的大小是 112 X 28,这意味着我想为每列显示 4 行。我怎样才能摆脱这个矩阵的上三角或下三角部分?因为这意味着每列对角删除 4 行 tril 或 triu 函数不起作用(它们用于方矩阵)。 谢谢

如果您有图像处理工具箱,您可以使用 imresize 调整上三角蒙版的大小,然后您可以将其用于 select 适当的数据

msk = imresize(triu(true(min(size(a)))), size(a), 'nearest');

% Just zero-out the lower diag
zeroed = msk .* a;

% Select the elements in the upper diagonal
upperdiag = a(msk);

如果您没有图像处理工具箱(和 imresize),您可以执行类似

的操作
msk = reshape(repmat(permute(triu(true(min(size(a)))), [3 1 2]), size(a,1)/size(a,2), 1), size(a));

您可以使用kron函数

kron(triu(ones(28)),[1 ;1 ;1 ;1])

我想出了一个解决方案 meshgrid

首先定义一个覆盖矩阵所有索引的网格

[X, Y] = meshgrid([1:28], [1:112]);

您想屏蔽所有高于(或低于)对角线 4x = y 的值。只需将掩码定义为 X 和 Y 值的函数即可。

mask = 4.*X >= Y; %>= Selects above the diagonal, <= selects below the diagonal

这是面具。请注意,轴不对称。

您可以使用此方法在网格上定义任何分隔线或功能。你甚至可以做一个抛物线

mask_parabola = (X-14).^2 >= Y;

有很好的答案,但也许这个可以作为使用 triu 函数的替代方法:

% image
img = rand(112, 28);

% utilize a square matrix to use triu command
temp = nan(112, 112);
temp(:, 1:4:end) = img;
temp = triu(temp, -3);

% put the relevant elements back
img = temp(:, 1:4:end);

您可以使用 bsxfun 创建掩码,如下所示:

M = 112; % number of rows
N = 28; % number of columns
mask = bsxfun(@le, (1:M).', (1:N)*round(M/N)); % create mask
data = data.*mask; % multiply your data matrix by the mask