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

remove rows from cell based on multiple conditions

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

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

我想找到任何代码等于 AAA 而数字不等于 4 的行。然后删除这些行留给我,

code   num
AAA    4
BBB    12
CCC    5

我尝试了以下方法,

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

此行为单元格类型的输入参数提供了未定义的函数 eq。

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

代号 AAA 5 AAA 6 血BB 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 应该 return 1 作为起始索引。

b = mod(k,3)

b = 1 2 0 1 1

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

column1 = floor(index/3+1) %output 1 2 4,也就是AAA

的行

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

现在您有了第 1 列的索引,其中包含值是 AAA 的字符串。现在你找到第 2 列的值 4s

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

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

编码愉快!

使用以下代码:

A(strcmp(A(:,1),'AAA') &([A{:,2}]'~=4),:) = []
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
}