在Matlab中从矩阵中删除行和列
我们应该如何有效地从Matlab中的矩阵中删除多行和多列? 向量包含应删除的索引.
How should we efficiently remove multiple line and columns from a matrix in Matlab? A vector holds indices that should be removed.
输入:t乘t矩阵
输出:(t-k)x(t-k)矩阵,其中k个不相邻的行和相应的列从输入矩阵中删除.
Output: (t-k) by (t-k) matrix in which k non-adjacent rows and corresponding columns are removed from input matrix.
这应该可以解决您的问题.
This should solve your problem.
matrix=randi(100,[50 50]);
rows2remove=[2 4 46 50 1];
cols2remove=[1 2 5 8 49];
matrix(rows2remove,:)=[];
matrix(:,cols2remove)=[];
第二个想法,如果您有索引,则首先使用功能ind2sub将这些索引转换为下标:
On the second thought, if you have indices, then first convert those indices to subscripts by using the function ind2sub as:
[rows2remove,cols2remove] = ind2sub(size(matrix),VecOfIndices);
现在,您将获得需要删除的元素的行索引和列索引.不能从矩阵中删除单个元素.因此,我假设您需要删除整个列和行.可以这样完成:
Now you will get row and column indices of elements which need to be removed. Individual elements cannot be removed from a matrix. So I am assuming that you need to remove the entire column and row. That can be done as:
rows2remove=unique(rows2remove);
cols2remove=unique(cols2remove);
matrix(rows2remove,:)=[];
matrix(:,cols2remove)=[];
如果要删除单个元素,请使用单元格数组或将这些元素替换为一些过时的值,例如9999.
If you want to remove individual elements then either use a cell array or replace those elements with some obsolete value such as 9999.