You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

高效获取矩阵中重复次数最多的值及占比的方法

Optimized Implementation for Finding Most Duplicate Value in Large Matrices

Got it, let's fix that slow performance for your mostduplicatevalue function. Handling a 1300x5000 matrix shouldn't take 5-6 seconds—MATLAB's vectorized, built-in functions are way faster for these kinds of counting tasks. Here's a streamlined, high-performance version:

function [MostDuplicateValue, MostDuplicatePerc] = mostduplicatevalue(A)
    % Convert matrix to a column vector (flattening removes dimension bias)
    A_flat = A(:);
    
    % Get unique values and their indices in the flattened array
    [unique_vals, ~, idx] = unique(A_flat);
    
    % Count occurrences of each unique value (uses optimized accumarray)
    counts = accumarray(idx, 1);
    
    % Find the index of the maximum count
    [max_count, max_idx] = max(counts);
    
    % Extract the most frequent value and calculate its percentage
    MostDuplicateValue = unique_vals(max_idx);
    MostDuplicatePerc = max_count / length(A_flat);
end

Why this is way faster:

  • Flattening first: Converting the matrix to a column vector simplifies the counting logic and lets MATLAB use its optimized array operations.
  • unique + accumarray: These are both low-level, optimized functions written in C under the hood—they're drastically faster than any manual loop you'd write in MATLAB.
  • Minimal overhead: We avoid unnecessary intermediate steps or data structures that would slow things down for large datasets.

Testing with your example:

If you run mostduplicatevalue([5 5 1 2 3 4 6 6 7 7 7 8 8 8 8]), it'll return 8 and 4/15 (≈0.2667), exactly as expected.

Edge case note:

If multiple values have the same maximum count, this implementation returns the first one that appears in the unique values list. If you need to handle ties differently (like returning all top values), you can modify the code to collect all indices where counts == max_count instead of just taking the first one.

For your 1300x5000 matrix, this should cut the runtime down to well under a second—likely just a few hundred milliseconds, depending on your hardware.

内容的提问来源于stack exchange,提问作者WJA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:26:07