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.

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

hahahahahaha. 36 seconds away from each other. Nice. Glad to see I was thinking along the same lines as you!
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

3 Comments

@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 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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.