【问题标题】:How to find the maximum number in a column for each group of data that are not 0 in Matlab如何在Matlab中找到每组不为0的数据的列中的最大数量
【发布时间】:2021-02-19 03:12:18
【问题描述】:

我有一张大表 (17001 x 35),对于一列(本例中的左侧),我需要获取每个组中的最大值。所以在这个例子中,答案是 56.6、57.2 和 87.5。理想情况下,答案将出现在刚刚列出的新向量列中。有什么帮助吗?看起来很简单,但我是新手,唉。

velocity marker
56.6 0
0 1
0 0
0 0
0 1
32.1 0
57.2 0
0 1
29.9 0
87.5 0
68.5 0
0 1

【问题讨论】:

  • 如何识别组?由1s?
  • 当有0时,值是否只能存在于对应的1标记之间?
  • 你的标题写着每组不为0的数据。但是,似乎组实际上是由第二列中的连续零定义的。你能澄清什么定义了一个群体吗?另外,您的数据是table 还是标准数值数组(矩阵)?
  • 例如,第二组是包含两个元素(其中标记为 0)还是三个(包括第一行,其中标记为 1)?如果是后者,为什么第一组不以 1 开头?

标签: matlab loops for-loop max


【解决方案1】:

如果保证在与标记为 1 对应的索引上不存在 Velocity 值,那么我们可以使用以下 for 循环方法来累积值,直到达到等于 1 的 marker。此时我们可以转储accumulator 并评估相应的最大值。 nnz() ~= 0 条件将检查以确保存储在 accumulator 中的整个组不包含零。

Velocity = [
56.6  0
0     1
0     0
0     0
0     1
32.1  0
57.2  0
0     1
29.9  0
87.5  0
68.5  0
0     1];


Velocity_Values = Velocity(:,1);
Markers = Velocity(:,2);
Accumulator = [];
Maximum_Added = 1;
for Index = 1: length(Velocity_Values)

if Markers(Index) ~= 1
Accumulator = [Accumulator; Velocity_Values(Index)]; 
end

%Dump accumulator%
if Markers(Index) == 1
    if(nnz(Accumulator) ~= 0)
    Maximums(Maximum_Added) = max(Accumulator);
    Maximum_Added = Maximum_Added + 1;
    end
    Accumulator = [];
end
 
end

Maximums = Maximums.';
disp(Maximums);

问题编辑前:

此方法使用find() 函数根据第二列中的1s 确定组的开始位置。这些指示起点的索引然后用于索引数组并检索对应于每个组的数组块。然后取每个块的最大值Group 并将其存储在一个名为Maximum_Of_Group 的数组中。要删除琐碎的0 情况,我们可以有条件地/逻辑地索引数组以仅获取与非零结果对应的索引~=0

Array = [
    0       1
    56.66   0
    0       1
    0       0
    0       0
    0       1
    317.18  0
    68.45   0
    107.44  0
    71.39   0
    61.00   0
    85.73   0
    131.90  0
    0       1
    138.28  0
    83.23   0
    0       1
    0       0
    0       0];

Group_Start_Indices = find(Array(:,2) == 1);
Maximum_Of_Group = zeros(length(Group_Start_Indices),1);
for Index = 1: length(Group_Start_Indices)
    
    
    Group_Start = Group_Start_Indices(Index);
    if(Index+1 < length(Group_Start_Indices))
    Group_End = Group_Start_Indices(Index+1)-1;
    else
    Group_End = length(Array);  
    end   
 
    Maximum_Of_Group(Index) = max(Array(Group_Start:Group_End,1));
    
end
    
Maximums = Maximum_Of_Group(Maximum_Of_Group ~= 0);
Maximums

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2014-12-13
    • 1970-01-01
    • 2014-11-04
    • 2018-04-18
    • 2017-09-23
    相关资源
    最近更新 更多