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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With