Sum: every nth column and groups/blocks of columns
1 回表示 (過去 30 日間)
古いコメントを表示
Hi:
Is there any way to improve this code?
Thanks
Dominic
%
% Flows between sectors of countries
% 3 countries with 4 sectors
% Row and column headings are the same C1S1 C1S2 ......C4S3 C4S4
%
c=3; % no. of countries
s=4; % no. of sectors
X=magic(c*s); % 12
%
% add every 4th (sth) column of a matrix: 1,5,9 ... 4,8,12
% - result 12x4 (sum by sector)
%
S=sum(X(:,1:s:end),2); % 1:4:end
for k=2:s % 2:4
SS=sum(X(:,(k):s:end),2);
S=horzcat(S,SS);
end
%
% add columns in blocks of 4: 1-4, 5-8, 9-12 - result 12x3 (sum by country)
%
C=sum(X(:,[1:s]),2); % [1:4]
x=(s+1):s:(c*s); % 5:4:12
y=(2*s):s:(c*s); % 8:4:12
for k=[x;y]
CC=sum(X(:,[k(1):k(2)]),2);
C=horzcat(C,CC);
end
0 件のコメント
採用された回答
Bruno Luong
2022 年 8 月 24 日
編集済み: Bruno Luong
2022 年 8 月 24 日
c=3; % no. of countries
s=4; % no. of sectors
X=magic(c*s); % 12
XX = reshape(X,size(X,1),s,[]);
S = sum(XX,3)
C = squeeze(sum(XX,2))
3 件のコメント
Bruno Luong
2022 年 8 月 24 日
Not only fewer line of code. It probably the fatest as it avoid matrix transposition.
その他の回答 (2 件)
Dyuman Joshi
2022 年 8 月 24 日
編集済み: Dyuman Joshi
2022 年 8 月 24 日
%comment lines removed
c=3; % no. of countries
s=4; % no. of sectors
X=magic(c*s); % 12
Vectorized solution
S1=reshape(sum(reshape(X,[],c),2),[],s)
C1=reshape(sum(reshape(X',s,[])),[],c)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!