Re: problem using strsplit [message #33521] |
Fri, 10 January 2003 06:52 |
David Fanning
Messages: 11724 Registered: August 2001
|
Senior Member |
|
|
Brian (briana@zetica.com) writes:
> I am relatively new to IDL and am probably missing something very
> obvious. I am reading in an ascii tab separated file into a string
> array. I know how many rows the file will contain but not how many
> columns hence the string array.
> I then try to use strsplit to separate all the columns but have an
> error - it seems that the columns are not seen as separate.
I think your problem is that StrSplit doesn't work on arrays.
It only works on scalars. I would read this tab-separated data
with a little routine like this:
FUNCTION File_Lines, filename
OPENR, unit, filename, /GET_LUN
str = ''
count = 0LL
WHILE NOT EOF(unit) DO BEGIN
READF, unit, str
count = count + 1
ENDWHILE
FREE_LUN, unit
RETURN, count
END
FUNCTION Read_Tab_Data, filename
; Calculate number of rows.
IF N_Elements(filename) EQ 0 THEN filename = 'file2.txt'
numrows = File_Lines(filename)
; Calculate number of columns.
oneline = ""
OpenR, lun, filename, /Get_Lun
ReadF, lun, oneline
numcolumns = N_Elements(StrSplit(oneline, /Extract))
; Rewind the file and read data.
Point_Lun, lun, 0
data = LonArr(numcolumns, numrows)
ReadF, lun, data
Free_Lun, lun
; Return the data.
RETURN, data
END
You won't need File_Lines if you have IDL 5.6, it is built
in. Call the Read_Tab_Data function like this:
IDL> data = Read_Tab_Data('file2.txt')
IDL> Help, data
DATA LONG = Array[5, 5]
Cheers,
David
--
David W. Fanning, Ph.D.
Fanning Software Consulting, Inc.
Phone: 970-221-0438, E-mail: david@dfanning.com
Coyote's Guide to IDL Programming: http://www.dfanning.com/
Toll-Free IDL Book Orders: 1-888-461-0155
|
|
|