help with find() or with logical indexing

I want to find array idx1, which is the values of array idx such that S(idx1) == j.
Example: Suppose
idx=[2 3 4 6 7 9 10 11], S=[1 1 1 1 2 2 3 3 3 4 4 4 4]
When j=1, I want idx1=[2 3 4];
when j=2, I want idx1=[6];
when j=3, I want idx1=[7 9];
when j=4, I want idx1=[10 11].
I tried idx1=idx(S==j)) and other ideas, but have not found the answer.
Thank you.

6 Comments

According to the question aren't you supposed to get idx1=[10 11 12] when j=4
I found an ugly answer to my question. If we assume that
j=1; idx=[2 3 4 6 7 9 10 11];
S=[1 1 1 1 2 2 3 3 3 4 4 4 4];
then
idx1=[];
for k=1:length(idx)
if S(idx(k))==j
idx1=[idx1 idx(k)];
end
end
gives the desired value for idx1. And it works for j=2, 3, 4 also. I suspect there is a much more elegant answer involving the clever use of array indexing.
Well if idx1 = [2,3,4], it's true that S(idx1) will equal 1. HOWEVER, if idx1 = [2,3,4,6] then S(idx1) will ALSO equal 1 for each value of idx1. What if idx1 = [2,3,4,6] - the first 4 values, which will return the first 4 values of S which are all 1. Why do you want idx1 = [2,3,4] instead of [2,3,4,6]?
And when you say that idx1 = 6, then S(idx1) equals S(6) which is 2, which is j for that case, but with a j of 2, it would also work to have idx1 = 5, because S(5) = 2. Why is idx1 not equal to [5,6]?
"According to the question aren't you supposed to get idx1=[10 11 12] when j=4"
No, only index values in idx can be returned, and 12 is not in idx.
I just tested the Answer I posted a couple of hours ago, and it produced exactly the desired output...
Thank you, Image Analyst and Walter, for your help. Context: Suppose I do 13 experimental trials: 4 trials on subject 1, 2 trials on subject 2, 3 trials on subject 3, and 4 trials on subject 4. Then array S(1:13) is the subject number for each trial. Eight trials yielded valid data, and those trial numbers are listed in idx(1:8). I want "idx1", which is a list of all the valid trials in subject 1. Then I want all the valid trials from subject 2, etc. The actual numbers of trials and subjects is much larger, and still growing. Walter provided an elegant solution.

Sign in to comment.

 Accepted Answer

intersect( find(S == j), idx )

1 Comment

Thank you Walter! Great answer. I did not know there was an intersect() function.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!