How should we efficiently remove multiple line and columns from a matrix in Matlab? A vector holds indices that should be removed.
Input: t by t matrix
Output: (t-k) by (t-k) matrix in which k non-adjacent rows and corresponding columns are removed from input matrix.
Delete the matrix A using the MLDeleteMatrix function. Enter this text in the cell and press Enter. The MLDeleteMatrix function deletes the matrix from the MATLAB Workspace.
Method 1: By using rmmissing( ) This function is used to remove missing entries or Nan values from a specified 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)=[];
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)=[];
If you want to remove individual elements then either use a cell array or replace those elements with some obsolete value such as 9999.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With