Cheng
Cheng

Reputation: 289

How to find the row index of a cell array that matches certain row of cells in MATLAB?

Say I have a cell array

CELLARRAY = 
{{[]} {[]} {[1 1 1]} {[]} {[]} {[1 1 1]};

{[]} {[]} {[1 1 1]} {[]} {[]} {[]};

{[]} {[]} {[]} {[]} {[]} {[]}}


A = {{[]} {[]} {[1 1 1]} {[]} {[]} {[]}}

Is there a smart way of finding the row index within CELLARRAY that matches A? and my answer would be 2?

Upvotes: 0

Views: 43

Answers (1)

Suever
Suever

Reputation: 65430

Probably the fastest way is going to be a for loop through the rows and MATLAB's JIT compiler should be able to optimize that decently.

matches = false(1, size(CELLARRAY, 1));

for k = 1:size(CELLARRAY, 1)
    matches(k) = isequal(CELLARRAY(k,:), A);
end

indices = find(matches);

Alternately, you could use something like cellfun to perform the operation for you but it will likely be slower

matches = cellfun(@(x)isequal(x, A), num2cell(CELLARRAY, 2)); 
indices = find(matches)

Upvotes: 3

Related Questions