READ array from a file [message #93085] |
Mon, 25 April 2016 07:09  |
Sapna Mishra
Messages: 66 Registered: December 2015
|
Member |
|
|
Hello All,
I have a file say:
Detail.txt with contents
name [1,2,3,4] [50.1,60.2,3.1,33.2]
I want to read this file, such as,
readcol,'Detail.txt',f='(A,I,F)',name,arr1,arr2
Such that I should get:
arr1[0]=1
arr2[0]=50.1
Can It be done?
Or other way out?
|
|
|
Re: READ array from a file [message #93109 is a reply to message #93085] |
Thu, 28 April 2016 10:28   |
Jeremy Bailin
Messages: 618 Registered: April 2008
|
Senior Member |
|
|
On Monday, April 25, 2016 at 9:09:25 AM UTC-5, Sapna Mishra wrote:
> Hello All,
>
> I have a file say:
> Detail.txt with contents
>
> name [1,2,3,4] [50.1,60.2,3.1,33.2]
>
> I want to read this file, such as,
>
> readcol,'Detail.txt',f='(A,I,F)',name,arr1,arr2
>
> Such that I should get:
> arr1[0]=1
> arr2[0]=50.1
>
> Can It be done?
> Or other way out?
You're probably going to have to parse something like that yourself. Do you know beforehand how many elements each array will have?
-Jeremy.
|
|
|
|
Re: READ array from a file [message #93134 is a reply to message #93118] |
Sun, 01 May 2016 00:24   |
Sapna Mishra
Messages: 66 Registered: December 2015
|
Member |
|
|
On Friday, April 29, 2016 at 10:12:18 AM UTC+5:30, Zachary Norman wrote:
> If you only have spaces ONLY between the name and the two arrays, then you can read the text file as a string array with:
>
> ;pre-allocate string array
> infile = 'C:\some\file.txt'
> nlines = file_lines(infile)
> strings = strarr(nlines)
> openr, lun, infile, /get_lun
> readf, lun, strings
> free_lun, lun
>
>
> Then you can split each line with:
>
>
> splitline = strsplit(strings[0], /extract)
> name = splitline[0]
> arr1 = splotline[2]
> arr2 = splitline[3]
>
>
> I'll let you figure out the rest for how you get the string representation of the arrays into actual arrays.
Yeah I tried this ..... worked fine...now the problem is
arr1= splitline[1] is an string array i don't know how to convert it into float array.
i tried with..
arr1= fltarr(splitline[1])
but its showing invalid type conversion. Any way out???
|
|
|
|
|
Re: READ array from a file [message #93137 is a reply to message #93136] |
Sun, 01 May 2016 02:35  |
Helder Marchetto
Messages: 520 Registered: November 2011
|
Senior Member |
|
|
What's the error now?
I guess that you are converting one element of the array and wonder why you don't get an array. If you know how many elements you have (let's call it nPts), you can do something like this:
arr1 = fltarr(nPts)
In the loop of i:
arr1[i] = float(splitted_string[2])
Cheers, Helder
|
|
|