1
$\begingroup$

I'm trying to append for every element of my for loop a complete table to my file myfile.dat, but everytime I run the loop I get it overwritten by the last cycle.

func[y_, m_] := y^2 + m ;
mX = 2;
For[i = 0, i < mX, i++,
 aa1 = Table[{func[y, i], y}, {y, 0.1, 0.2, 0.005}];
 dat1 = Flatten /@ Transpose[{aa1}];
 Export["/Users/federico/Documents/Wolfram Mathematica/myfile.dat", 
  dat1, "Table"]]

Any idea? Thanks

Edit. Here the result from one comment:

func[y_, m_] := y^2 + m ;
mX = 2;
t = Table[{y, func[y, i]}, {y, 1, 2, 0.1}, {i, 0, mX - 1}];
dat1 = Flatten /@ Transpose[{t}];
Export["/Users/federico/Documents/Wolfram Mathematica/myfile.dat", \
dat1, "Table"]

which gives something close to the solution, but still it prints the y column twice unfortunately

Edit. here the want to be output

image

Edit. In this way it works but I've to get rid of those commas and brackets

func[y_, m_] := y^2 + m;
mX = 2;
    SetDirectory["/Users/federico/Documents/Wolfram Mathematica"];
    For[i = 0, i < mX, i++,
     For[y = 1, y <= 2, y = y + 0.1, {i, y, func[y, i]} >>> myfile];]
    FilePrint["myfile"]
$\endgroup$
10
  • $\begingroup$ You could ues a stream with Write. I think you could also use PutAppend. $\endgroup$
    – lericr
    May 12, 2022 at 16:40
  • $\begingroup$ Could you use this instead and then flatten as required? t = Table[{func[y, i], y}, {y, 0.1, 0.2, 0.005}, {i, 0, mX - 1}] $\endgroup$
    – Syed
    May 12, 2022 at 16:44
  • $\begingroup$ @Syed may be working, only problem is it saves the y column twice. Just edited the post with your suggestion $\endgroup$
    – Fredrigo6
    May 12, 2022 at 18:23
  • $\begingroup$ If you include the desired output, it will be easier to match it. I suggested this as Table does the same thing as a For loop, but can't say that I understand your problem yet. $\endgroup$
    – Syed
    May 12, 2022 at 19:08
  • $\begingroup$ I want to create mX tables where the first column is y and the second one is f(y,i). I'll include the output wait $\endgroup$
    – Fredrigo6
    May 12, 2022 at 19:38

1 Answer 1

3
$\begingroup$
func[y_, m_] := y^2 + m;
mX = 2;
t1 = Join @@ 
  Table[{i + 1, y, func[y, i]}, {i, 0, mX - 1}, {y, 1, 2, 0.1}]

t1 // TableForm

$$\left( \begin{array}{ccc} 1 & 1. & 1. \\ 1 & 1.1 & 1.21 \\ 1 & 1.2 & 1.44 \\ 1 & 1.3 & 1.69 \\ 1 & 1.4 & 1.96 \\ 1 & 1.5 & 2.25 \\ 1 & 1.6 & 2.56 \\ 1 & 1.7 & 2.89 \\ 1 & 1.8 & 3.24 \\ 1 & 1.9 & 3.61 \\ 1 & 2. & 4. \\ 2 & 1. & 2. \\ 2 & 1.1 & 2.21 \\ 2 & 1.2 & 2.44 \\ 2 & 1.3 & 2.69 \\ 2 & 1.4 & 2.96 \\ 2 & 1.5 & 3.25 \\ 2 & 1.6 & 3.56 \\ 2 & 1.7 & 3.89 \\ 2 & 1.8 & 4.24 \\ 2 & 1.9 & 4.61 \\ 2 & 2. & 5. \\ \end{array} \right)$$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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