7

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.

Jose Luis
  • 3,307
  • 3
  • 36
  • 53
user25004
  • 1,868
  • 1
  • 22
  • 47

1 Answers1

16

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.

Autonomous
  • 8,935
  • 1
  • 38
  • 77
  • Suppose if I enter a number say 5, i wanna remove the `5th row` and `5th column` from the `matrix`, can you suggest any `single line code` to do that? – noufal Apr 06 '13 at 09:44
  • i have a very large matrix, and I cannot copy my matrix to remove some parts of it, i need to use the data and clear the data that i use and make another array from that space, how should i do that? – Ehsan Jul 15 '15 at 07:00
  • @Ehsan Why do you need to make its second copy? This should work: `matrix(rows2remove,:)=[]; matrix(:,cols2remove)=[];` – Autonomous Jul 16 '15 at 01:22
  • 1
    @noufal `matrix = matrix([1:4, 6:end], [1:4, 6:end]);` – rayryeng Nov 17 '15 at 21:07