Matlab 基于另一个矩阵对矩阵列求和

Matlab 基于另一个矩阵对矩阵列求和,matlab,Matlab,我有两个大小相同的矩阵 First matrix: weights 800 x 1250 Second matrix: country_code 800 x 1250 每一列都是一个观察值 我想做的是根据国家代码对权重矩阵中的每列求和。下面的例子可以更好地解释这一点 Weight country_code 20 25 30 15 20 12 12 12 12 12 40 10 20 5 10

我有两个大小相同的矩阵

First matrix: weights 800 x 1250
Second matrix: country_code 800 x 1250
每一列都是一个观察值

我想做的是根据国家代码对权重矩阵中的每列求和。下面的例子可以更好地解释这一点

Weight                          country_code

 20   25  30  15  20        12   12  12  12  12
 40   10  20  5   10        10   10  10  10  10
 10   35  25  50  40        5    5   5   5   5
 30   30  25  30  30        12   12  12  12  12

List of Country Codes      Result Matrix    
 5                         10   35  25  50  40                       
 10                        40   10  20  5   10                 
 12                        50   55  55  45  50
我的代码如下,但没有给出正确的答案

int_ccy - is the number of unique country codes
ccy - is a vector of the unique country codes

 for t = 1 : int_ccy
    wgts(t, :) = nansum(Weight(country_code==ccy(t, 1), :));    
 end                 

下面应该可以解决这个问题,虽然有一种更好的方法可以使用逻辑索引(我认为),但我无法马上回忆起它:

for t = 1 : int_ccy;
    wgts(t,:) = sum(weight .* (country_code == ccy(t, 1)), 1);    
end  

下面应该可以解决这个问题,虽然有一种更好的方法可以使用逻辑索引(我认为),但我无法马上回忆起它:

for t = 1 : int_ccy;
    wgts(t,:) = sum(weight .* (country_code == ccy(t, 1)), 1);    
end  

以下是一种矢量化方法:

%%\ Sample Variables
Weight=[20 25 30 15 20; 40 10 20 5 10; 10 35 25 50 40; 30 30 25 30 30];
country_code=repmat([12;10;5;12],1,4)
list=[5;10;12];

%%\ Sum each column in the weights matrix based on the country_code
[~, countrylines, ~]=intersect(country_code,list)
sum(Weight(countrylines,:),1)

以下是一种矢量化方法:

%%\ Sample Variables
Weight=[20 25 30 15 20; 40 10 20 5 10; 10 35 25 50 40; 30 30 25 30 30];
country_code=repmat([12;10;5;12],1,4)
list=[5;10;12];

%%\ Sum each column in the weights matrix based on the country_code
[~, countrylines, ~]=intersect(country_code,list)
sum(Weight(countrylines,:),1)

由于
country\u code
的所有列都相等,因此可以使用矩阵乘法在一行中完成

然后


由于
country\u code
的所有列都相等,因此可以使用矩阵乘法在一行中完成

然后


国家/地区代码是否总是按列显示?是的,它是按列显示的。国家/地区代码是否总是按列显示的?是的,它是按列显示的