如何在单元格数组中找到特定单元格? [英] How do I find a specific cell within a cell array?

查看:201
本文介绍了如何在单元格数组中找到特定单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含1x2个单元格的单元格数组。例如。 deck = {{4,'c'},{6,'s'} ...... {13,'c'} ...... {6,'d'}}

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

如何找到特定单元格的索引?例如,我想找到值为 {13,'c'} 的单元格的索引。

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'}.

谢谢!

推荐答案

我建议的另一种方法是分别对每一列进行操作。我们可以在每列上使用逻辑运算符来搜索单元格数组中包含第一列中特定数字的卡片,然后在第二列中搜索特定的套装。为了表示匹配,我们将检查这两个输出相交的位置。我们可以通过在完成后将两个输出与逻辑 AND 组合来实现此目的:

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

因为 deck 是一个嵌套的单元格数组,所以我展开它以使它成为一个2D单元格数组,其中每一行表示一张牌。它存储在 deck_unroll 中。一旦我这样做,我进一步展开单元格,以便第一列放入一个数字数组,我们搜索一个特定的数字(在你的例子中为13),第二列放入一个字符串数组,在那里我们搜索一个特定的字符(在您的示例中为'c')。这是在 cat 从特定列中提取每个元素,然后用这些元素构造一个数组。

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.

这篇关于如何在单元格数组中找到特定单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆