0
$\begingroup$

I'm very new to Mathematica.

I want import a file in which the first colum is a function f1, the second another function f2. So the file looks like this:

f1       f2
12       7
14       11
18       15
13       7

I try to import that file with:

Import["testfile.dat","Table"]

Now, however, I have one table in which are both functions! So I want to split that table in the function f1 and f2. Maybe via a different method of importing?

So it my target is actually that it should look like this:

f1 = {12, 14, 18, 13}
f2 = {7, 11, 15, 7}
$\endgroup$
  • 1
    $\begingroup$ Look up Transpose[]. $\endgroup$ – J. M.'s discontentment Feb 15 '16 at 18:15
  • $\begingroup$ {f1,f2} = Transpose[data] or f1 = data[[All, 1]]. $\endgroup$ – Szabolcs Feb 15 '16 at 18:15
  • $\begingroup$ Thanks for the reference, those solutions also worked perfectly! $\endgroup$ – TheCheatsrichter Feb 15 '16 at 19:32
1
$\begingroup$

I made a text file with the following lines

f1       f2  
12       7  
14       11
18       15
13       7

saved it my desktop and then imported it with

data = Import[FileNameJoin[{$HomeDirectory, "Desktop", "test.dat"}]]

To transform the imported data as requested, I evaluated

Clear[f1, f2]
Evaluate[Symbol /@ data[[1]]] = Transpose[Rest[data]];
{f1, f2}

{{12, 14, 18, 13}, {7, 11, 15, 7}}

Update

As often happens with me, I have had second thoughts about the above code. It bothers me that the variables names are given explicitly in the code; they should be determined from the imported table. My revision is

With[{vars = First[data], vals = Rest[data]},
  Evaluate[Clear @@ vars; Symbol /@ vars] = Transpose[vals]]
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks for the detailed response. Is this perfomance wise also the best solution? Because I have to import 2 functions with 16000 samples each. This script runs on a raspberry pi in an endless loop. $\endgroup$ – TheCheatsrichter Feb 15 '16 at 19:28
  • $\begingroup$ @TheCheatsrichter. Best performance as compared to what other methods? I have done no performance testing on my code. I believe the data transformation step will be faster than the import step. All the operations appearing in the transformation code are well-optimized built-in functions, so should be quite fast. $\endgroup$ – m_goldberg Feb 16 '16 at 14:06
1
$\begingroup$

I use ImportString as I don't have your file. Just swap it for your Import.

With[{\[FormalX] = Symbol@First@#},
   \[FormalX] = Rest@#] & /@ Transpose@
ImportString["f1       f2
   12       7
   14       11
   18       15
   13       7", "Table"]

Then

f1
(* {12, 14, 18, 13} *)

f2
(* {7, 11, 15, 7} *)

Hope this helps.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.