【问题标题】:Find indices in each column and intelligently average the values in the same column based on the indices查找每列中的索引,并根据索引对同一列中的值进行智能平均
【发布时间】:2017-10-22 07:44:15
【问题描述】:

我有一个矩阵,每一列都是相互独立的。也就是说,每一列的最小值为0,最大值为1,这是一个概率。但是,不必每列只包含一个1。当我尝试查找包含1 的每一列的索引时,这会给我带来一个问题。索引将用于提取另一个矩阵的值,比如位置矩阵。如果它包含两个1,则应取平均值。示例代码:

prob=[rand(4,1) rand(4,1) rand(4,1)];
max_prob_idx=find(prob==1);
%extract from position matrix
pos=rand(4,3);
extracted_pos=pos(max_prob_idx); %this is wrong, look example below

从上面的代码中,我会得到一个extracted_pos的列向量。这搞砸了我的数据提取。数字:

prob=[1    0    1 
      0.1  1    0.8
      0.2  0.5  1
      0.3  1    1]

max_prob_idx=[1; 6; 8; 9; 11; 12];

pos=[1 5 9
     2 6 10
     3 7 11
     4 8 12]

extracted_pos=[1; 6; 8; 9; 11; 12]; %6x1 matrix

我在两者之间遗漏了一些东西,因此我最终预期的 extracted_pos 将是

extracted_pos=[1; (6+8)/2; (9+11+12)/3]; %3x1 matrix

我知道这看起来很混乱,但我想不出任何其他方式来解释我的问题。这可以做到吗?或者还有其他方法可以做到这一点?提前致谢!

【问题讨论】:

    标签: matlab matrix indexing


    【解决方案1】:
    % generate position matrix
    pos = reshape(1:numel(prob),size(prob)); % technically the reshape is not necessary, a vector 1:numel(prob) would do it too, but I find it nicer.
    % empty NaN matrix
    P = nan(size(prob)); 
    % extract 1 values
    P(prob==1) = pos(prob==1);  % with real data you might have to make a check with tolerance
    % mean of each column
    extracted_pos = mean(P,1,'omitnan');
    

    extracted_pos 当然可能包含浮点数 - 如何处理它们取决于你

    【讨论】:

    • 你是个天才!非常感谢!
    • nanmean 来自统计和机器学习工具箱。将mean'omitnan' 一起使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多