0

When I try to feed the following function an array, it gives me the following error: % Expression must be a scalar or 1 element array in this context: . How to modify such that I can either give it a scalar or array?


; 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
DavidH
  • 415
  • 4
  • 21
SilvanD
  • 325
  • 2
  • 14

1 Answers1

2

This should do it:

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

EDIT: For pedagogical reasons, I will show the ugly (untested) looping solution, but you should never do this in 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
mgalloy
  • 2,356
  • 1
  • 12
  • 10
  • Thanks for responding, Mgalloy. Your solution works, but my original aim was to learn how to loop through arrays (or scalars) using the kind of control statement provided above--do you know how I might be able to achieve that? – SilvanD Feb 20 '16 at 13:36
  • In IDL, you do not want to loop through elements of an array when you don't have to; there is a definite performance penalty. I will submit another non-vectorized solution. – mgalloy Feb 20 '16 at 16:14