如何在我定义的函数中接受数组

How to accept arrays in my defined function

当我尝试向以下函数提供数组时,它给出了以下错误:% Expression must be a scalar or 1 element array in this context: 。如何修改以便我可以给它一个标量或数组?


; return integer -1, 0, or 1, depending on whether x is less than 0, equal to 0, or greater than 0, respectively
function whatisit, x
  case 1 of
    (x lt 0): y=-1
    (x eq 0): y=0
    (x gt 0): y=1
  endcase
  return, y
end

应该这样做:

function whatisit, x
  return, x gt 0 - x lt 0
end

编辑:出于教学原因,我将展示丑陋的(未经测试的)循环解决方案,但您永远不应该在 IDL 中这样做:

function whatisit, x
  n = n_elements(x)
  result = bytarr(n)
  for i = 0L, n - 1L do begin
    case 1 of
      x[i] lt 0: result[i] = -1
      x[i] eq 0: result[i] = 0
      x[i] gt 0: result[i] = 1
    endcase
  endfor
  return, size(x, /n_dimensions) eq 0 ? result[0] : result
end