views:

543

answers:

3

I am trying to import a data set to Mathematica. The problem is that I cannot have the imported data as regular numbers in Mathematica. They are imported as "list". So, I cannot use them in the equations I need:

Import["out.dat", "Data"]
{{5.7, 4.3}, {-1.2, 7.8}}
Array[cc, {2, 2}]
For[i = 1, i <= 2, i++, 
 For[j = 1, j <= 2, j++, 
  cc[i, j] = Take[Import["out.dat", {"Data", i}], {j, j}]]]

Now, I need c[1,1] to be 5.7 but it is {5.7} as you see:

cc[1, 1]
{5.7}
+1  A: 

Firstly to access an array element use "[[ ]]"

    c = {{5.7, 4.3}, {-1.2, 7.8}};
    c[[1, 1]]
    Out=5.7

Update.

c[[1,1]] used to access to 2 dimensional array (matrix) to access simple array use c[[1]]

    In[27]:= Import["d:\\dat.out", "Table"]    
    Out[27]= {{5.7, 4.3, -1.2, 7.8}}    
    In[28]:= %[[1]]    
    Out[28]= {5.7, 4.3, -1.2, 7.8}    
    In[29]:= IntegerPart[#] & /@ %    
    Out[29]= {5, 4, -1, 7} 
etc...

Update 2.

If cc[1, 1] == {5.7} then use array element selector again:

cc[1,1][[1]]
Konoplianko
Thanks,out.dat:5.7 4.3-1.2 7.8I get this error when using cc[[1,1]]:cc[[1, 1]]Part::partd: Part specification cc[[1,1]] is longer than depth of \object. >>cc[[1, 1]]
Matin
Could you post your new code. My guess would be you are not using the "Table" option for Import.
Davorak
+1  A: 

Hi

This does depend on the precise format of the contents of your dat file. For example, if the file contains just numbers tab (or space) and line separated like this:

5.7   4.3
-1.2  7.8

Then the statement

cc = Import["out.dat"]

loads the data directly into the variable cc. Then, using the correct notation for array subscripting, ie [[ and ]] not [ and ] you can access the numbers in each element of the array as you wish. It's very very simple. If your input file is more complex you should either (a) simplify it, or (b) study the various options and parameters for the Import[] function.

As a general rule if you find yourself writing loops in Mathematica you are not doing it right.

The form

c[1,1] = 5.7

is, to Mathematica, a function definition. It looks very much like an assignment to an element in an array, which means that you can define all sorts of interesting objects which are functions but look like arrays, or arrays which look like functions. Of course, this is because an array is a function from index space to the set of elements. But to Mathematica [ and ] delimit arguments to a function.

Based on your question and your comments I suspect that you are a beginner with Mathematica. The on-line documentation is very good, but you have to read it to get any value from it.

Regards

Mark

High Performance Mark
A: 

I think this does what you want:

mat = {{5.7, 4.3}, {-1.2, 7.8}};
Do[c[i, j] = mat[[i, j]], {i, 2}, {j, 2}]

Then c[1, 1] returns 5.7 (for example).

--Mark

Mark Fisher