通过施加条件删除特定行

Delete specific rows by imposing a condition

我有一个由名称列和数据列组成的结构。

我需要通过对特定名称施加条件来删除一系列行。 我在另一个练习中使用了这段代码,它似乎没问题,但我猜它不正确:

    sn = {'Adattamento ad una distrib._HID',...
          'Adattamento ad una distrib._HI1',...
          'TUTTI','Modelling','Sheet37','Sheet52'}; % fogli da escludere

   SheetNames = {S.Name}; %% 

    for jj = 1:length(sn)
      SheetNames = {S.Name};
      S = S(~strncmp(SheetNames, sn(jj),jj));
      %jj = numel(sn)-1; % aggiorna l'indice
    end  

----------------------------更新------ ------------------------------ 我明白了问题。

我的S.Name结构是这样制作的:

SheetNames = {S.Name};



  This is {S.Name} :

    {'Ar1';'Adattamento ad una distrib._HID';'Adattamento ad una distrib._HI1';...;'Ar2';'Ar35';...;
'Cos1';'Cos2';'Cos31';...;'Tex1';'Tex2';....;
'Sheet37_HID';'Tex8';.....;'Tex30';'Tu1';'Tu2';'Tu3';...;'Tu32';
'TUTTI';'Modelling';'Sheet52'}

如果

 sn = {'Adattamento ad una distrib._HID',...
          'Adattamento ad una distrib._HI1',...
          'TUTTI','Modelling','Sheet37','Sheet52'};

最终结构S,将不再包含以ATM[=开头的名字34=],S

S = 1x128 循环后变成 S = 1x91

我能想到的最简单的解决方案是使用 stringismember:

function S2 = q56456298()
%% Generate a dataset:
ROWS = 128;
isUnwanted = randn(ROWS,1) > 0 ;
S = repmat(struct('Name',[], 'Data', []), 1, ROWS);
for ind1 = 1:ROWS
  if isUnwanted(ind1)
    S(ind1).Name = sprintf('Unwanted%u', ind1);
  else
    S(ind1).Name = sprintf('Useful%u', ind1);
  end
  S(ind1).Data = array2table(rand(randi(200),4));
end

%% Remove all "Unwanted fields"
names = string({S.Name}).'; % Here we collect all names, and make it a string array.

toRemove = "Unwanted" + (1:ROWS).'; % This simulates your "sn" array.
[~, idxToDelete] = ismember(toRemove, names);
S2 = S(~idxToDelete); % The result only contains "Useful" rows.

让数据定义为

S(1).Name = 'Ar1'; S(1).Data = [1 2 3];
S(2).Name = 'Adattamento ad una distrib._HID'; S(2).Data = 'abcd';
S(3).Name = 'Adattamento ad una distrib._HI1'; S(3).Data = [true; false];
S(4).Name = 'Ar4'; S(4).Data = {'4' '5'};
sn = {'Adattamento ad una distrib._HID',...
      'Adattamento ad una distrib._HI1',...
      'TUTTI','Modelling','Sheet37','Sheet52'};

然后,您可以使用ismember和逻辑索引如下:

result = S(~ismember({S.Name}, sn));