# How to export iterated values of a function into a text file?

I have a 3x3 textfile 3.txt of numerical values. Each column corresponds to a,b,c respectively. I have a function f(d,e) as given below.

<< NumericalCalculus

data = ReadList["3.txt", {Number, Number, Number}]

ndata = 3;

Do[a[i] = data[[i, 1]], {i, 1, ndata}]

Do[b[i] = data[[i, 2]], {i, 1, ndata}]

Do[c[i] = data[[i, 3]], {i, 1, ndata}]

Chi[d, e] := Sum[((c[i]*d) - (e*a[i]))^2/b[i]^2, {i, 1, ndata}]


I would like to export all values of f(d,e) into a separate textfile, for specific ranges of variables d and e, Could anybody help ?

• The definition of f is incorrect, should be f[d_, e_]. Use Table to iterate over the ranges for d and e. Sep 20, 2021 at 14:17
• @RohitNamjoshi Sorry it was an error, actually it is Chi[d, e]. Could i obtain a textfile now ? Sep 20, 2021 at 14:25
• No, check my previous comment. The function definition is incorrect, the arguments in the definition need to be patterns, Chi[d_, e_]. Sep 20, 2021 at 17:22
• You can use Export["YourOutfile.txt", YourDataToExport, "Table"] Sep 20, 2021 at 19:10
• @fred85 Let me clarify. Suppose i include say {d, -10, 10} and {e, -10, 10} in the definition of my function Chi. I want all values of Chi for the given ranges d and e, to be exported to my Outfile.txt. Then, what should i write in YourDataToExport  part in Export[] ? Sep 21, 2021 at 11:05

SeedRandom[1];
ndata = 3;
data = RandomReal[10, {ndata, ndata}]

Do[a[i] = data[[i, 1]], {i, 1, ndata}]
Do[b[i] = data[[i, 2]], {i, 1, ndata}]
Do[c[i] = data[[i, 3]], {i, 1, ndata}]

chi[d_, e_] := Sum[((c[i]*d) - (e*a[i]))^2/b[i]^2, {i, 1, ndata}]

chiValues = Table[{d, e, chi[d, e]}, {d, -10, 10}, {e, -10, 10}] // Flatten[#, 1] &

Export["chi_values.csv", chiValues // Prepend[{"d", "e", "chi"}]]

• I have two more concerns too. If my function  chi  consists of more than one sum, say sum[..]+sum[..]+... and now my  chi  is a function of, say 4 or 5 variables. How to flatten my results now? Also, How to get rid off the complex part of each number in my final text file ? Sep 29, 2021 at 12:47
• @Shareef The second argument of Flatten needs to be number of variables - 1. So for 4 variables Flatten[#, 3] &. If you just want the real part of chi then Re[chi[...]] in Table`. Sep 29, 2021 at 14:01