检查单元格中的条目是否在单元格中 [英] Check if entries in a cell are in a cell arrary

查看:88
本文介绍了检查单元格中的条目是否在单元格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个单元格

A = {[3,0], [2,1]}

和一个单元格数组

B = {[4,-1],[3,0];      
      [-1,4],[-3,5];
      [3,0],[2,1];
      [2,1],[-1,4]}.

我想找到A的第一个或第二个条目都显示在B中的索引,而B的两个条目都在其中出现的行除外.

I want to find the indices where both the first or second entry in A shows up in B excluding the row in B where both entries of A show up.

在此示例中,对于B中的行,我应该得到类似[1 4]的内容.我一直在尝试使用cellfuncell2mat来解决这个问题,但请继续尝试.

In this example I should get something like [1 4] for the rows in B. I've been trying to figure this out using cellfun and cell2mat but keep stumbling.

推荐答案

我将通过将单元格数组转换为适当尺寸的数字数组,然后使用ismember来解决此问题.

I would approach this problem by converting my cell arrays to numeric arrays of appropriate dimensions, and then use ismember.

以下示例说明了此方法如何在问题中的示例单元格数组上工作:

The following example illustrates how this method works on the example cell arrays in the question:

%# Build the example cell arrays
A = {[3,0], [2,1]};
B = {[4,-1],[3,0];      
     [-1,4],[-3,5];
     [3,0],[2,1];
     [3,0],[3,0];
     [2,1],[-1,4]};

%# Get the number of elements in A, and the length of the first element
K = size(A, 2);
J = length(A{1, 1});

%# Convert cell arrays to usefully shaped numerical matrices
ANumVec = cell2mat(A);
ANum = reshape(ANumVec, K, J)';
BNum = cell2mat(B);

%# Find matches of 1*2 vectors in ANum in sets of two columns of BNum 
I1 = ismember(BNum(:, 1:J), ANum, 'rows');
I2 = ismember(BNum(:, J+1:end), ANum, 'rows');
I3 = ismember(BNum, ANumVec, 'rows');

%# Find all indices where there was exactly 1 match (ie omit cases of no matches and cases of 2 matches)
MainIndex = I1 + I2;
MainIndex(I3) = 0;
Soln = find(MainIndex > 0);

一些要点:

1)此方法查找B中所有元素在B的第一列或第二列中的B中所有行的索引,不包括完全对应于B的行.

1) This method finds the indices of all rows in B where an element of A lies in the first or second column of B, excluding the situation where A corresponds exactly to a row of B.

2)如果A中有多行,则此方法将失败.但是,将A作为大小为1 * N的单元格数组是很可靠的,其中N表示任意数量的1 * 2数字矢量.因此,可以通过首先将A重塑为1 * N单元阵列来避免单行限制.

2) This method will fail if there are multiple rows in A. However, it is robust to A being a cell array of size 1*N, where N denotes some arbitrary number of 1*2 numeric vectors. Thus the single row limitation can be circumvented by first reshaping A to a 1*N cell array.

3)使用逻辑运算符==测试等效性.除非您有理由相信先验输入不会显示任何浮点错误,否则使用浮点数可能会很危险.

3) Equivalence is tested using the logical operator ==. This can be dangerous with floating point numbers unless you have reason to believe a priori that your inputs will not exhibit any floating point error.

4)我无法动摇的感觉是,有一种更有效的方法可以解决此问题,但是我暂时没有看到它. :-)

4) I can't shake the feeling that there is a much more efficient way to solve this problem, but that I'm not seeing it at the moment. :-)

这篇关于检查单元格中的条目是否在单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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