How do I sum the values of sections of a table?
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Macy
am 8 Feb. 2023
Beantwortet: Tushar Behera
am 8 Feb. 2023
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 Kommentare
Akzeptierte Antwort
Tushar Behera
am 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 Kommentare
Weitere Antworten (1)
Voss
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Numeric Types finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!