Home > database >  Remove all the fields with specific index
Remove all the fields with specific index

Time:12-26

I got a struct with few fields, let's call it "ST". I remove all the lines with flag=0. I do simply:

ST.Name(flag==0)=[];
ST.Age(flag==0)=[];
ST.Sex(flag==0)=[];
ST.School(flag==0)=[];
%...
% ...
ST.Nationality(flag==0)=[]; 

It works, but I want some smarter way, as I will have many lines, and might forget something. So I tired to work smarter:

fn = fieldnames(ST);
ST.fn(flag==0)=[];

And I get an error: Deletion requires an existing variable. What is the right way to write it?

CodePudding user response:

% Find the indices of the elements with flag==0
indices = find(flag==0);

% Loop through each field of the struct
fn = fieldnames(ST);
for i = 1:numel(fn)
    % Delete the elements at the indices from the current field
    ST.(fn{i})(indices) = [];
end

CodePudding user response:

A simple way to do that is using structfun. For example, let

ST.Age = [10 20 30 40];
ST.Sex = {'male' 'female' 'male' 'female'};
flag = [0 0 1 1];

Then

ST = structfun(@(field) field(flag~=0), ST, 'UniformOutput', false);

gives

ST = 
  struct with fields:

    Age: [30 40]
    Sex: {'male'  'female'}
  • Related