Find value in cell array and return index

Hello
I have a cell array of the form: A={[1,2,3;4,5,6],[11,22],[33;55;66;7]}; Now I want the code to return the index of e.g. value "5", i.e. A{:,1}(2,2). How do I write this?
Thank you for any help LF

 Accepted Answer

Jan
Jan on 22 Sep 2017
Edited: Jan on 22 Sep 2017
What have you tried so far? How do you want to store the results?
The solution is more or less trivial with a loop:
A = {[1,2,3;4,5,6], [11,22], [33;55;66;7]}
s = 5;
nA = numel(A);
Match = cell(1, nA);
for iA = 1:nA
match{iA} = find(A{iA} == s);
end
Or perhaps:
nA = numel(A);
Match = cell(nA, 3); % Pre-allocate
iMatch = 0;
for iA = 1:nA
[i1, i2] = find(A{iA} == s);
if ~isempty(i1)
iMatch = iMatch + 1;
Match{iMatch, 1} = iA; % Index of the cell
Match{iMatch, 2} = i1; % Row and column indices
Match{iMatch, 3} = i2;
end
end
Match = Match(1:iMatch, :); % Crop unused elements
Now Match{:, 1} is the cell element with a match, and Match{:, 2:3} are the row and column indices.
Maybe this is enough:
Match = cellfun(@(c) find(c == s), A, 'uniform', false);
Then Match{k} contains the linear indices, if matching elements are found.

4 Comments

Sorry, it seems not to work.
The first code returns match-Array with [4][][]. Why 4 and not 5, since "5" has the linear indexing 5 in the first cell Array? But, actually I would Need [2,2][][] as an answer, to tell me that "5" is in the first cell Array, row 2 and column 2.
The second code returns 1x1 cell-Match Array with value 1 in it.
Can I work with ind2sub, perhaps?
It does work! The linear index of 5 is 4 not 5! But if you want to extract row and column you just need to adapt the code Jan gave you. Store the row and column return from find and put it in the match cell array.
[row,col] = find(A{iA} == s);
match{iA} = [row,col];
"Sorry, it seems not to work. The first code returns match-Array with [4][][]. Why 4 and not 5, since "5" has the linear indexing 5 in the first cell Array?"
Actually the code is correct, and 4 is the linear index of the value 5. This is the whole array and its corresponding linear indices:
>> [1,2,3;4,5,6] % your matrix
ans =
1 2 3
4 5 6
>> [1,3,5;2,4,6] % linear indices
ans =
1 3 5
2 4 6
Of course you don't have to believe us or the MATLAB documentation, you can simply try it yourself.
Would this method work to locate a string/number element in another array? I keep getting Arrays have incomptible sizes for this operation.

Sign in to comment.

More Answers (0)

Asked:

on 22 Sep 2017

Commented:

on 2 Jun 2021

Community Treasure Hunt

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

Start Hunting!