0

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]; 
EBH
  • 10,350
  • 3
  • 34
  • 59
Tariq Islam
  • 97
  • 10

2 Answers2

2

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
EBH
  • 10,350
  • 3
  • 34
  • 59
1

You could do it like this

>>> union(union(x(r(1),:),x(r(2),:)),x(r(3),:))

ans =

  0     1     2     3     4     5     7     8     9    10    12

or set up a for loop that iterates over the vector r to compute all the unions

Dan
  • 1,466
  • 1
  • 13
  • 27