3

I want to know the index of row of cell consisting of particular array in particular column...

Example:

C{1,1} = [1 2 3];
C{1,2} = [4 5 6];
C{2,1} = [11 12 13];
C{2,2} = [14 15 16];

I want to get index as 1 when I search for [1 2 3] in column 1 (or) 2 when I search for [14 15 16] in column 2. I tried using

index = find([C{:,1}] == [1 2 3])

But didn't get. Please help

1
  • and what do you want, when you search for [4 5 6]? Commented Apr 12, 2015 at 10:50

2 Answers 2

2

Use cellfun in combination with strfind and isempty or isequal directly.

pattern = [1 2 3];

out = cellfun(@(x) ~isempty(strfind(x,pattern)),C)
%// or as suggested by Luis Mendo
out = cellfun(@(x) isequal(x,pattern),C)

ind = find(out)

if the order within the arrays does not matter, also the following using ismember and all is possible:

out = cellfun(@(x) all(ismember(x,pattern)),C)

out =
     1     0
     0     0

ind =
     1

Do all the arrays have the same length n? Then you could use a more vectorized approach with an optional if-condition to see if your result is valid. It may is not necessary, depending how sure you are about your pattern input.

n = 3;
pos = strfind([C{:}],pattern)
ind = [];
if mod(pos,n) == 1, ind = (pos - 1)/n + 1, end

Both variants give you the linear index, means for pattern = [14 15 16]; it would return 4. To get the row indices you need an additional step:

[~,row_ind] = ind2sub(size(C),ind)
Sign up to request clarification or add additional context in comments.

5 Comments

But theismember approach would also "find" [3 2 1] for example. Perhaps use out = cellfun(@(x) isequal(x,pattern), C)
@Luis Mendo, I haven't thought about that! thanks! one could use strfind as well like in my second approach.
@thewaywewalk I hadn't seen that other approach. Nice use of strfind. It's not well known (or documented?) that this function also works for numbers
@LuisMendo I haven't seen it documented, but it gets used a couple of times recently.
@thewaywewalk Yes, I've used it myself in the past, and it's really handy
0

Another approach Using pdist2 instead of ismember and all from the other answer

pattern = [1 2 3];
out = cellfun(@(x) pdist2(x,pattern)==0,C);
ind = find(out)

Gives the same result as the other answer.

Comments

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.