matlabmatrixvectorset-union

How to take union of matrix rows that are represented by another vector?


I want to take the union of some of the rows of a matrix x. The row numbers of the rows whose union has to be taken are given by vector r. Is there any built-in function in MATLAB that can do it?

x = [1  2  4  0  0; 
     3  6  5  0  0;
     7  8 10 12  9;
     2  4  6  7  0;
     3  4  5  8 12];

r = [1, 3, 5]; 

Solution

  • I think this will work for you - first, take the submatrix x(r,:) with the rows you want, and then find all the unique values in it:

    unique(x(r,:))
    
    ans =
         0
         1
         2
         3
         4
         5
         7
         8
         9
        10
        12