1

I have [sentence cross words] logical matrix where value = 1 shows presence of a word in that sentence and 0 shows absence like as follows:

0 0 1 1

1 0 1 0

0 0 0 1

1 1 0 0

I have done some processing and selected specific words i.e. 2 & 3

result = 2 3

Now, I want to select only those rows in which value of words 2 & 3 are equal to 1 and return there row number as follows:

row = 1 2 4

This should be done for every word that is in result variable - thanks.

Afzaal Ahmad
  • 187
  • 1
  • 12

2 Answers2

3

Think you are looking for something like this, assuming A as the input binary array -

result = [2 3]; %// select words by IDs
row = find(any(A(:,result),2))

Sample run -

A =
     0     0     1     1
     1     0     1     0
     0     0     0     1
     1     1     0     0
row =
     1
     2
     4

For fun-sake, you can also use matrix-multiplication as an alternative approach -

row = find(A(:,result)*ones(numel(result),1))
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • 1
    hahahahahaha. 36 seconds away from each other. Nice. Glad to see I was thinking along the same lines as you! – rayryeng Apr 08 '15 at 08:20
3

First choose the columns that you want to extract and create a matrix that concatenates all of these columns together. Next, use any and operate along the columns in combination with find to obtain the desired locations.

Therefore, given your logical matrix stored in X, do:

ind = [2 3];
matr = X(:,ind);
vals = find(any(matr, 2));

With your above example, we get:

vals =

     1
     2
     4
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • @Divakar - Thanks :). +1 to you too... don't know why there was a downvote. I was legitimately working on this answer at the same time you were. I hate it when people downvote and they don't give a reason. – rayryeng Apr 08 '15 at 08:22
  • @rayryeng thanks for your answer it works, wanted to ask you if there is a way in which i can pass a variable for example: `result` which has words sored and it should automatically select which columns to select like `ind = result;` rather than giving `ind = [2 3];` because in my real scenario there are large number of columns selected – Afzaal Ahmad Apr 08 '15 at 08:32
  • 1
    Just use `ind = result;`. As long as `result` is a vector of columns, then the above code will work. I just did `ind = [2 3];` in order to go with your example. – rayryeng Apr 08 '15 at 08:38