How do I find a specific cell within a cell array?

半城伤御伤魂 提交于 2019-11-28 10:31:19

问题


Let's say I have a cell array containing 1x2 cells. eg. deck = {{4,'c'},{6,'s'}...{13,'c'}...{6,'d'}}

How can I find the index of a specific cell? E.g I want to find the index of the cell with the values {13,'c'}.

Thanks!


回答1:


Another method I can suggest is to operate on each column separately. We could use logical operators on each column to search for cards in your cell array that contain a specific number in the first column, followed by a specific suit in the second column. To denote a match, we would check to see where these two outputs intersect. We can do this by combining both outputs with a logical AND when we're done:

deck = {{4,'c'},{6,'s'},{13,'c'},{6,'d'}};
target_card = {13, 'c'};

deck_unroll = vertcat(deck{:});    
a1 = cat(1, deck_unroll{:,1}) == target_card{1};
a2 = cat(1, deck_unroll{:,2}) == target_card{2};
found = a1 & a2  

found =

     0
     0
     1
     0

Because deck is a nested cell array, I unrolled it so that it becomes a 2D cell array where each row denotes one card. This is stored in deck_unroll. Once I do this, I further unroll the cells so that the first column gets placed into a numeric array and we search for a particular number (13 in your example) and the second column gets placed into a string array where we search for a particular character ('c' in your example). This is done with the help of cat to extract each element from a particular column and we construct an array out of these elements.




回答2:


Try cellfun with isequal:

>> deck = {{4,'c'},{6,'s'},{13,'c'},{6,'d'}};
>> targetCell = {13,'c'};
>> found = cellfun(@(c) isequal(c,targetCell),deck)
found =
     0     0     1     0

cellfun let's you check anyway you want (not just isequal). For example, if you want to check based on the string element in each cell:

>> targetLetter = 'c';
>> found = cellfun(@(c) strcmp(c{2},targetLetter),deck)
found =
     1     0     1     0


来源:https://stackoverflow.com/questions/27746614/how-do-i-find-a-specific-cell-within-a-cell-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!