How do I sum the values of sections of a table?
19 views (last 30 days)
Show older comments
Hi there. I have this data, for which I created a new vector called schoolyear. How do I sum the total number of students for each schoolyear and save each value into a new vector or matrix?
So for example, the new vector totalstudents should read: 50, 66.
One suggestion I have been given is to use a for loop with possibly an if/then.
Note this is a sample of a much larger data set.
Thank you.
clc;
close all;
clear all;
table_a = readtable('Data1.xlsx');
%Create the new vector, schoolyear
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:)
0 Comments
Accepted Answer
Tushar Behera
on 8 Feb 2023
Hi Macy,
I believe you want to group the students by the year and find the total.
This can be acheived by using the function "splitapply". This function apply a function to a group of data. For example:
clc;
close all;
clear all;
table_a = readtable('Data1.xlsx');
%Create the new vector, schoolyear
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:)
g=findgroups(table_a.schoolyear)%find the groups in the data
grouped_students_total= splitapply(@sum, table_a.students, g);%get the sum from the groups
Here in "grouped_students_total" you will find your desired result. To know more about "splitapply" you can follow the following documentation:
I hope this resolves your query.
Regards,
Tushar
0 Comments
More Answers (1)
Voss
on 8 Feb 2023
table_a = readtable('Data1.xlsx');
%Create the new vector, schoolyear
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:);
Here's one way:
table_summary = groupsummary(table_a,'schoolyear',@sum,'students')
0 Comments
See Also
Categories
Find more on Numeric Types 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!