Optimizing code when using xlsread

10 views (last 30 days)
Ramya
Ramya on 15 Feb 2015
Answered: Jacob Jaminet on 16 Feb 2015
I am using the xlsread function to call data from an excel sheet in order to create a matrix using data from that excel sheet. I am trying to create a matrix recording the mean, median, min, max, and standard deviation of the data. Here is my code for calling up the excel sheet:
Data = xlsread('Caregivers.xlsx');
CaregiverAge = xlsread('Caregivers.xlsx', 'Caregivers', 'B2:B101');
CaregiverIncome = xlsread('Caregivers.xlsx', 'Caregivers', 'C2:C101');
Durationofcaregiving = xlsread('Caregivers.xlsx', 'Caregivers', 'D2:D101');
I then made variables for data analysis functions:
A =[mean2(CaregiverAge);mean2(CaregiverIncome);mean2(Durationofcaregiving)];
B =[median(CaregiverAge); median(CaregiverIncome);median(Durationofcaregiving)];
C = [min(CaregiverAge); min(CaregiverIncome);min(Durationofcaregiving)];
D = [max(CaregiverAge); max(CaregiverIncome);max(Durationofcaregiving)];
E = [std(CaregiverAge); std(CaregiverIncome); std(Durationofcaregiving)];
I finally made a matrix summarizing these above variables:
Summary = [A, B, C, D, E];
As shown, there are several lines of coding and I was wondering if there was a way to optimize this coding so that it will be easier to read and understand. Any help is greatly appreciated. Thank you!

Answers (2)

dpb
dpb on 16 Feb 2015
You've got all the data in the first xlsread; use it directly...
[mn,md,mi,mx,st]=grpstats(Data,[],{'mean','median','min','max','std'});
Summary=[mn;md;mi;mx;st];
where the return variables correlate to the statistics listed in the argument list to grpstats. By default Matlab works by column. The above is the equivalent of writing
mn=mean(Data);
md=median(Data);
...

Jacob Jaminet
Jacob Jaminet on 16 Feb 2015
dpb did a great job with his answer. I would only recommend you focus your data set before working with it in case there is more data in the excel sheet and you only want to work with those three columns.
Data = xlsread('Caregivers.xlsx', 'Caregivers', 'B2:D101');
This creates a 3 column matrix of the data you want. You don't have to worry about any non-numeric data it might overlap as Matlab should only grab the numeric data you want. More focused if there is more data in your excel sheet and you only want those 3 data sets. Then you can go ahead and use the code suggested by dpb.
[mn,md,mi,mx,st]=grpstats(Data,[],{'mean','median','min','max','std'}); Summary=[mn;md;mi;mx;st];
Hope it helps!

Categories

Find more on Data Import from MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!