How to sum up specific columns based on the values in a different column
7 views (last 30 days)
Show older comments
Matlab coding. So basicially, I have an excel sheet with data that spans 9 years, and for every year, there is data for the 12 months. So the data looks like this:
2022 12 data data data
2022 12 data data data
2022 11 data data data
2022 11 data data data
2022 10 data data data
I want my code to sum all the data within columns 3:16 of the excel sheet for the rows marked a certain month, and then add that sum into one column of a new vector. All data within all years marked by month 12 will be in col 1, all data within all years marked by month 11 in col 2, etc until I have a 1x12 vector which holds the sum of that month in each column
I tried a while loop but my "sumbymonth" vector never produces anything
monthcounter = 12;
colcounter = 1;
while monthcounter >= 1
SumByMonth = sum(yeardata(yeardata(:,3:16)==monthcounter,:);
colcounter = colcounter+1;
monthcounter=monthcounter-1;
end
thank you for your help everyone
0 Comments
Accepted Answer
Cris LaPierre
on 29 Oct 2023
Moved: Walter Roberson
on 29 Oct 2023
If your only group is Month, then I'd just sum the columns first, and then use groupsummary to sum data from the same month.
yeardata = rand(10,14);
Year = [2022; 2022; 2021; 2021; 2020; 2020; 2019; 2019; 2018; 2018];
month = [12; 12; 11; 11; 10; 10; 9; 9; 8; 8];
data = [table(Year, month), array2table(yeardata)]
data.SumData = sum(data(:,3:16),2);
SumByMonth = groupsummary(data,"month","sum","SumData")
You could also use rowfun
rowfun(@sum,data, "InputVariables", "SumData","GroupingVariables","month")
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!