• 【Matlab笔记_17】查找数组中相同元素


    案例一:找到数组中相同元素所在位置索引

    方法:使用unique函数用于找到唯一的元素和它们在原数组中的索引。然后,histc函数用于计算每个唯一元素的出现次数,并通过ismember函数找到重复元素在原数组中的索引。最后,通过find函数找到包含重复元素的索引

    % 创建一个包含重复内容的数组
    myArray = [1, 2, 3, 4, 2, 5, 6, 1];
    
    % 使用unique函数查找唯一的元素和它们的索引
    [uniqueElements, ~, indexInUnique] = unique(myArray);
    
    % 使用ismember函数找到重复元素在原数组中的索引
    duplicateIndices = find(ismember(indexInUnique, find(histc(indexInUnique, 1:numel(uniqueElements)) > 1)));
    
    % 显示结果
    if isempty(duplicateIndices)
        disp('数组没有重复的元素。');
    else
        disp('数组包含重复的元素。');
        disp('重复元素的索引是:');
        disp(duplicateIndices);
    end
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    案例二:找到相同元素第一次出现的索引

    方法:对案例一进行稍微修改,使用accumarray函数用于在每个唯一元素的索引位置上存储第一次出现的索引。然后,通过histc函数找到重复元素,并使用这些索引找到相同元素第一次出现的位置。

    % 创建一个包含重复内容的数组
    myArray = [1, 2, 3, 4, 2, 5, 6, 1];
    
    % 使用unique函数查找唯一的元素和它们的索引
    [uniqueElements, ~, indexInUnique] = unique(myArray);
    
    % 使用accumarray函数找到每个元素第一次出现的索引
    First_idx= accumarray(indexInUnique(:), (1:numel(myArray)).', [], @min);
    
    % 找到重复元素的索引
    result= First_idx(histc(indexInUnique, 1:numel(uniqueElements)) > 1);
    
    % 显示结果
    if isempty(result)
        disp('数组没有重复的元素。');
    else
        disp('数组包含重复的元素。');
        disp('重复元素第一次出现的索引是:');
        disp(result);
    end
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    生成代理:人类行为的交互模拟(Generative Agents: Interactive Simulacra of Human Behavior)
    [Js进阶]bind、call、apply三个方法
    Part6:Pandas 三类函数对缺失值的处理
    两种基于时间窗口的限流器的简单实现
    智慧校园信息化管理系统的方案设计与实施
    SpringBoot无侵入式实现API接口统一JSON返回
    Redisson—分布式服务
    程序员必看内容连续集之 SpringBoot 01自定义注解
    flutter 加.then方法
    dind(docker in docker)学习
  • 原文地址:https://blog.csdn.net/weixin_43771393/article/details/133984848