如何在m×1矩阵中查找重复元素及其所在行索引?
Hey, let's figure out why your code isn't working and fix it step by step.
What's Wrong with Your Current Code?
Your line k = find(~unique(A)); doesn't target duplicate indices at all. Here's the breakdown:
unique(A)returns the sorted unique values from your array, not any indicator of duplicates.- Applying
~(logical NOT) to those values just flips true/false for each entry (turning non-zero values to false, zero to true)—this has no connection to identifying which positions in the original array have repeated elements. No wonder you're getting incorrect results!
Correct Solution for Integer/Exact Values
Let's use your sample array to build the right approach:
A = [4 5 5 5 7 8 4]; % Your sample 1×7 array % Step 1: Get unique values + map each element in A to its unique group [unique_vals, ~, group_idx] = unique(A); % Step 2: Count occurrences of each unique value counts = accumarray(group_idx, 1); % Step 3: Filter values that appear more than once (duplicates) duplicate_vals = unique_vals(counts > 1); % Step 4: Find all indices in A that match these duplicate values RowValues = find(ismember(A, duplicate_vals));
When you run this, RowValues will output [1;2;3;4;7]—exactly the result you expected!
Handling Floating-Point Rational Numbers
For your actual data with values like -0.0038 or 1.3438, you need to account for floating-point precision errors. Direct equality checks might fail if values are slightly different due to computation. Adjust the code with a tolerance parameter:
A = [-0.0038, 1.3438, 1.3438, -0.0038, 2.1]; % Example with floats tol = 1e-6; % Adjust this based on your required precision [unique_vals, ~, group_idx] = unique(A, 'tol', tol); counts = accumarray(group_idx, 1); duplicate_vals = unique_vals(counts > 1); RowValues = find(ismember(A, duplicate_vals, 'tol', tol));
The 'tol' parameter tells MATLAB to treat values within that tolerance as equal, avoiding false negatives from tiny floating-point differences.
How Each Part Works
unique(A, 'tol', tol): Grabs distinct values (accounting for floating-point tolerance) and maps each element inAto its corresponding unique value viagroup_idx.accumarray(group_idx, 1): Counts how many times each unique value appears inA.counts > 1: Identifies which unique values are duplicates (appear more than once).ismember(...) + find(): Creates a logical array marking duplicate elements, then converts those positions to row indices.
内容的提问来源于stack exchange,提问作者Matte

