Sum groups of columns

5 views (last 30 days)
Millie Johnston
Millie Johnston on 24 Sep 2022
Commented: Millie Johnston on 24 Sep 2022
Hello,
I have a 10x4600 matrix and I would like to sum all the content in 50 column groups, i.e., sum all of the contents in cols 1-50 then 51-100 etc., greating a 1x92 matrix.
What is the best way to do this?
Any advice is much appreciated

Accepted Answer

Turlough Hughes
Turlough Hughes on 24 Sep 2022
Here's another option:
a = rand(10,4600);
b = mat2cell(a,height(a),repmat(50,1,width(a)/50));
result = cellfun(@(x) sum(x,'all'),b)
result = 1×92
248.7251 241.6021 250.5905 252.4766 255.2734 248.3946 249.4391 246.7810 251.7672 249.2486 251.6410 245.3834 253.4206 259.4736 245.6898 251.8762 241.4311 255.5951 253.3935 244.1446 249.9427 254.0830 253.6857 245.3108 252.2754 247.8954 251.1564 250.9599 244.3892 250.7689

More Answers (1)

Davide Masiello
Davide Masiello on 24 Sep 2022
Edited: Davide Masiello on 24 Sep 2022
Example
M = rand(10,4600);
n = 50;
for idx = 1:size(M,2)/n
S(idx) = sum(M(:,n*(idx-1)+1:n*idx),'all');
end
size(S)
ans = 1×2
1 92
S
S = 1×92
251.4836 239.6670 250.9846 257.7764 245.8032 240.2424 251.1242 243.9000 242.6086 251.5657 248.0851 255.3710 247.0354 250.5451 246.9072 253.7353 246.9934 245.9795 248.1267 239.6427 242.5911 244.9033 248.7932 260.2680 251.8315 242.8476 254.6372 262.0528 252.7250 259.5901

Tags

Community Treasure Hunt

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

Start Hunting!