根据多个条件从单元格中删除行

时间:2015-01-07 10:50:04

标签: matlab

我有一个尺寸为50 x 2的单元格。表格的一个子集如下所示。

code   num
AAA    5
AAA    6
BBB    12
AAA    4
CCC    5

我想找到代码等于AAA并且num不等于4的任何行。然后删除这些行以留下我,

code   num
AAA    4
BBB    12
CCC    5

我尝试了以下内容,

indx_remove = rf_cell(:,1)=='AAA'&& rf_cell(:,2)〜='4';

这一行为我提供了类型为cell的输入参数的未定义函数eq。

3 个答案:

答案 0 :(得分:2)

使用以下代码:

A(strcmp(A(:,1),'AAA') &([A{:,2}]'~=4),:) = []

答案 1 :(得分:1)

我相信我这样做很难,但我希望这不是太愚蠢。

代码编号     AAA 5     AAA 6     BBB 12     AAA 4     CCC 5

%生成代码矢量和num矢量

code = ['AAA', 'AAA', 'BBB', 'AAA','CCC']

代码= AAAAAABBBAAACCC

num = [5;6;12;4;5]

k = strfind(code, 'AAA')%找到你的索引

k = 1 2 3 4 10%因为矢量代码只是子字符串的串联,所以需要对索引进行排序

%在这里,你可以做一些聪明的事情,你的选择,我使用模数,因为你的字符长度是3个字符,模3应该返回1作为起始索引。

b = mod(k,3)

b = 1 2 0 1 1

index = k(find(b==1))%1,4,10返回

column1 = floor(index/3+1)%输出1 2 4,这是具有AAA

的行

check = num(floor(column1/3+1))%只是一个检查阶段,输出5 6 4的num。

现在,对于具有AAA值的字符串,您具有第1列的索引。现在,您可以在第2列找到值4s

column2 = find(num==4)%输出4

如果column1和column2包含相同的数字并删除该值(引用索引),则可以编写if语句来删除索引[编号4]

快乐的编码!

答案 2 :(得分:1)

ind = cellfun(@(x,y) strcmp(x,'AAA') & y~=4, {A{:,1}}, {A{:,2}}) '
A(find(ind==0),:)
ans =
{
  [1,1] = BBB
  [2,1] = AAA
  [3,1] = CCC
  [1,2] =  12
  [2,2] =  4
  [3,2] =  5
}

详细

% // Create the values

A = {'AAA',    5;
'AAA'   , 6;
'BBB'   , 12;
'AAA'   , 4;
'CCC'   , 5};

%// Create a cell array of the values

{A{:,1}}, {A{:,2}}

ans =
{
  [1,1] = AAA
  [1,2] = AAA
  [1,3] = BBB
  [1,4] = AAA
  [1,5] = CCC
}
ans =
{
  [1,1] =  5
  [1,2] =  6
  [1,3] =  12
  [1,4] =  4
  [1,5] =  5
}

%// Create an anonymous function that will be applied to each element of our cell.
%// It will take the elements of the first cell (represented by `x` in the anonymous function)
%// and compare it to `AAA` and the elements of the second cell (`y`) and compare it to `4`.
%// The result is an array with the logical result of the conditions.

ind = cellfun(@(x,y) strcmp(x,'AAA') & y~=4, {A{1:size(A,1),1}}, {A{1:size(A,1),2}}) '

ind =

1
1
0
0
0

%// Then find the rows where these were zero as we wanted to exclude those values

A(find(ind==0),:)
ans =
{
  [1,1] = BBB
  [2,1] = AAA
  [3,1] = CCC
  [1,2] =  12
  [2,2] =  4
  [3,2] =  5
}