Folks I am a beginner in Mathematica and have a simple question regarding loops: Here's the problem, I have a dataset of with four columns and I need to loop over each row. So the matrix in which my data is has dimensions of n*4, (n rows).

If there was only one column then the problem is straightforward: I would do something like,

For[i=1;x=0, i < n; i++, x = custF[i];Print[x]]

where custF is custom function I built.

The problem is the function I built has four parameters not one. What I need is a loop like ForEach, which loops over each row and finds values of the function with all 4 parameters. Any help would be deeply appreciated!

  • $\begingroup$ could you provide a small sample of your dataset? Is it correct to assume you want to pass row by row; meaning your custom function takes 4 arguments? Or do you want to pass element by element as they are found in rows? $\endgroup$ May 16, 2016 at 21:58
  • $\begingroup$ Thanks for answering! so it's row by row. I do not it need element by element. $\endgroup$ May 16, 2016 at 21:59
  • $\begingroup$ By "dataset" do you mean Dataset? $\endgroup$
    – march
    May 16, 2016 at 22:00
  • $\begingroup$ Okay, if you are using Dataset - how about dataset[All, custF], where dataset is your dataset and custF is your function $\endgroup$ May 16, 2016 at 22:00
  • $\begingroup$ Here's my datamatrix: $\endgroup$ May 16, 2016 at 22:00

1 Answer 1



(*Arbitrary data*) 
list = RandomInteger[{1, 10}, {4, 4}]

(*Apply list to custom function*)
f @@@ list


{f[2, 8, 6, 5], f[3, 1, 6, 7], f[9, 2, 10, 5], f[9, 2, 5, 9]}


If you are loading an Excel spreadsheet, to apply row by row you could do something similar as described above.

In order to load up an Excel spreadsheet, see example below:



(*Import it into Mathematica*)
data =  Flatten[Import["C:\\Users\\-e\\Documents\\data.xlsx"], 1]

I use Flatten to remove additional {}


{{1., 2., 3., 4.}, {3., 4., 5., 5.}, {7., 8., 7., 1.}, {4., 7., 3., 6.}}

Then carry out same operation as in first example:

f @@@ data

where f is your custom function which takes 4 arguments as an input and on the output of the above you should have something like:

{f[1., 2., 3., 4.], f[3., 4., 5., 5.], f[7., 8., 7., 1.], f[4., 7., 3., 6.]}


List Manipulation


Import spreadsheet


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.