1

If I have a pre-existing array, X, and I want to extract values from X and put them into a new array, new_x, how do I do that?

I understand that I can take parts of the arrays using range functions, but I am extracting data from X using conditions written using for loops.

jenn
  • 11
  • 1
  • 5

1 Answers1

2

There are a number of different ways, depending upon how large your array is. The simplest approach is to just concatenate the values into the new array. For example:

new_x = []
for i=0,n_elements(x)-1 do begin
  if x[i] "matches condition" then new_x = [new_x, x[i]]
endfor

This will work fine for small arrays but becomes very expensive and slow for large arrays, since you are always re-allocating the memory.

A better approach is to use a "flag" array, then use "WHERE" to extract the indices. For example:

flag = BYTARR(N_ELEMENTS(x))
for i=0,n_elements(x)-1 do begin
  if x[i] "matches condition" then flag[i] = 1
endfor
new_x = x[WHERE(flag, /NULL)]

The best way would be to eliminate the for loop completely, but this may not be possible. For example, let's say you just wanted X values that were within a certain data range:

new_x = x[WHERE(x ge 5 and x le 10, /NULL)]

Hopefully one of these methods will work for your problem.

Chris Torrence
  • 452
  • 3
  • 11
  • 1
    It's worth noting that these methods only work for IDL >= 8.0 (specifically the `/NULL` keyword to `WHERE()` and the empty array initializer) – sappjw Jul 13 '16 at 11:35
  • Thanks so much! Your response was really helpful. – jenn Jul 13 '16 at 16:34
  • `x[where()]` should work work fine in IDL<8.0 as long as you protect from `where()` returning `-1` if it doesn't find any elements matching the conditions (or if you can safely assume that at least one element will meet conditions). – EL_DON Oct 06 '16 at 17:13