Search code examples
arraysstructidlfits

IDL - Struct of Arrays to Array of Structs


From a FITS-Table I read data, and get a Struct containing the table, where each tag represents a column.

Is there a way to reformat the Struct of Arrays to an Array of Structs? So that one Struct in the Array represents a Row?


General solution made by @mgalloy (see below):

function SoA2AoS, table

  if (table eq !NULL) then return, !NULL

  tnames = tag_names(table)
  new_table = create_struct(tnames[0], (table.(0)[0]))
  for t = 1L, n_tags(table) - 1L do begin
    new_table = create_struct(new_table, tnames[t], (table.(t))[0])
  endfor

  new_table = replicate(new_table, n_elements(table.(0)))

  for t = 0L, n_tags(table) - 1L do begin
    new_table.(t) = table.(t)
  endfor

  return, new_table

end

Solution

  • You can do it without knowing the names of the tags too (untested code):

    ; suppose table is a structure containing arrays
    tnames = tag_names(table)
    new_table = create_struct(tnames[0], (table.(0))[0]
    for t = 1L, n_tags(table) - 1L do begin
      new_table = create_struct(new_table, tnames[t], (table.(t))[0])
    endfor
    table = replicate(table, n_elements(table.(0)))
    for t = 0L, n_tags(table) - 1L do begin
      new_table.(t) = table.(t)
    endfor