0
$\begingroup$

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`

SetDirectory["C:/Users/vmsha/Downloads"];

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 ?

$\endgroup$
7
  • 1
    $\begingroup$ The definition of f is incorrect, should be f[d_, e_]. Use Table to iterate over the ranges for d and e. $\endgroup$ Commented Sep 20, 2021 at 14:17
  • $\begingroup$ @RohitNamjoshi Sorry it was an error, actually it is Chi[d, e]. Could i obtain a textfile now ? $\endgroup$
    – Shareef
    Commented Sep 20, 2021 at 14:25
  • $\begingroup$ No, check my previous comment. The function definition is incorrect, the arguments in the definition need to be patterns, Chi[d_, e_]. $\endgroup$ Commented Sep 20, 2021 at 17:22
  • $\begingroup$ You can use Export["YourOutfile.txt", YourDataToExport, "Table"] $\endgroup$
    – fred85
    Commented Sep 20, 2021 at 19:10
  • $\begingroup$ @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[] ? $\endgroup$
    – Shareef
    Commented Sep 21, 2021 at 11:05

1 Answer 1

2
$\begingroup$
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"}]]
$\endgroup$
2
  • $\begingroup$ 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 ? $\endgroup$
    – Shareef
    Commented Sep 29, 2021 at 12:47
  • $\begingroup$ @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. $\endgroup$ Commented Sep 29, 2021 at 14:01

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.