【IDL】数组求交集、并集和差集的函数

IDL对两个数组求交集、并集和差集的函数,从以往的blog里面翻出来的,转帖出来,备查。

;+-------------------------------------------------------------------------------------------------
;| 数组求并集
;+-------------------------------------------------------------------------------------------------
function setunion, a, b
  ;
  compile_opt StrictArr
  if n_elements(a) eq 0 then return, b    ;A union NULL = a
  if n_elements(b) eq 0 then return, a    ;B union NULL = b
  return, where(histogram([a,b], OMin = omin)) + omin ; Return combined set
end
;+-------------------------------------------------------------------------------------------------
;| 数组求交集
;+-------------------------------------------------------------------------------------------------
function setintersection, a, b
  ;
  compile_opt StrictArr
  
  minab = min(a, Max=maxa) > min(b, Max=maxb) ;Only need intersection of ranges
  maxab = maxa < maxb
  ;
  ; If either set is empty, or their ranges don't intersect: result = NULL.
  if maxab lt minab or maxab lt 0 then return, -1
  r = where((histogram(a, Min=minab, Max=maxab) ne 0) and $
    (histogram(b, Min=minab, Max=maxab) ne 0), count)
    
  if count eq 0 then return, -1 else return, r + minab
end
;+-------------------------------------------------------------------------------------------------
;| 数组求差集
;+-------------------------------------------------------------------------------------------------
function setdifference, a, b
  ;
  compile_opt StrictArr
  ;
  ; = a and (not b) = elements in A but not in B
  mina = min(a, Max=maxa)
  minb = min(b, Max=maxb)
  if (minb gt maxa) or (maxb lt mina) then return, a ;No intersection...
  r = where((histogram(a, Min=mina, Max=maxa) ne 0) and $
    (histogram(b, Min=mina, Max=maxa) eq 0), count)
  if count eq 0 then return, -1 else return, r + mina
end
;数组交集、并集和差集测试
pro test_array
  arr1 = [1,2,3,4]
  arr2 = [3,4,5,6]
  print,'交集',setintersection(arr1,arr2)
  print,'并集',setunion(arr1,arr2)
  print,'差集',setdifference(arr1,arr2)
end

 

 

posted @   地理遥感生态网平台  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示