MATLAB: Sum the TWh/year (the last column) when the name of the countries (the first column) are similar.

energylinkstocountries

sum the TWh/year (the last column) when the name of the countries (the first column) are similar (File is attached.) Please help me!

Best Answer

That’s relatively straightforward with the unique and accumarray functions, and using the table function to present the output.
The Code:
[d,s,r,] = xlsread('BINH DUONG solar.xlsx','DNI'); % Import Data
TWhy = d(:,5); % Total Watt-hours/year
[Countries,ia,ic] = unique(s(2:end,1), 'stable'); % Unique Countries, Retain Original Order
TotalWhPerYear = accumarray(ic, TWhy); % Add TWh/y By Country
TableOfResults = table(Countries, TotalWhPerYear); % Create Table Of Results