%% Split Two Data Variables and Apply Function
% Calculate the variances of the differences in blood pressure readings for groups of patients, and display the results. The blood pressure readings are contained in two data variables. To calculate the differences, use a function that takes two input arguments.
% Load blood pressure readings and smoking data for 100 patients from the data file patients.mat.

load patients
whos Systolic Diastolic Smoker

%
% Define func as a function that calculates the variances of the differences between systolic and diastolic blood-pressure readings for smokers and nonsmokers.  func requires two input arguments.

func = @(x,y) var(x-y);

%
% Use findgroups and splitapply to split the patient data into groups and calculate the variances of the differences. findgroups also returns group identifiers in smokers. The splitapply function calls func once per group, with Systolic and Diastolic as the two input arguments.

[G,smokers] = findgroups(Smoker);
varBP = splitapply(func,Systolic,Diastolic,G)

%
% Create a table that contains the variances of the differences, with the number of patients in each group.

numPatients = splitapply(@numel,Smoker,G);
T = table(smokers,numPatients,varBP)

% Copyright 2015 The MathWorks, Inc.