MATLAB: Creating a loop to use all columns in a dataset array

datasetStatistics and Machine Learning Toolbox

Hello , i have a data set with 10 columns.The first column contains the names of the variables and the 9 next contain the data for the variables across 9 periods. I want , for each period ,to take the data which are lower than the data's median .I use the following command for the first period: s1=data(data.mv1<median(data.mv1),{'Name','mv1',}), where mv1 is the header of the first period's column and s1 a new dataset which contains only the variables i want. My question is , can i write a (for) loop that will automatically do this for the whole 9 periods, thus giving me s1,s2,…,s9?

Best Answer

data = dataset({('a':'z').','names'},{rand(26,2),'mv1','mv2'});
EDIT
% Retrieve column names/variables (from second onwards)
varnames = data.Properties.VarNames(2:end);
nV = numel(varnames);
% Preallocate
C = cell(1,nV);
% Loop per each column (variable)
for v = 1:nV
idx = data.(varnames{v}) < median(data.(varnames{v}));
C{v} = data.(varnames{v})(idx);
C{v} = data(idx,[1 v]);
end