Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathematica functions

  1. Jan 6, 2010 #1
    Hi guys ,

    I'm a little new with Mathematica and I'm trying to write down some functions.
    the first one is writing a functions that square the elements in a vector , recursively ,
    using patterns .

    so , I tried this one :
    x = Range[1, 10];
    sq[sum_,list_] := Sum[sum*sq[sum, list[n - 1]], _list]

    but it isn't working . what's the problem ?

    2. The second function is writing a function that sorts a list of numbers , by checking each time two numbers that are adjacent .

    if I write this : sort[list_] :=
    how can I tell mathematica that I want to use an actual list of numbers ? can I say list ?

    thank you
  2. jcsd
  3. Jan 7, 2010 #2


    User Avatar
    Science Advisor
    Homework Helper

    There seem to be multiple problems.
    First of all, the assignment in the second line should probably be delayed (:= instead of =) because you want to substitute "list" for whatever value is passed. Also, list[n - 1] is a function call, you meant list[[n - 1]]? Anyway, what is n in that expression? Finally, what are you doing with the "Sum" expression? Sum[f[x], {x, a, b}] sums the values of f[x] for a <= x <= b.

    Can you maybe explain more clearly what you want the function to do (e.g. if you input x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, do you want it to output {1, 4, 9, 16, 25, 36, 49, 64, 81, 100} ?)

    2) How do you mean: "use an actual list of numbers"? You can call sort[x] (where x is defined as in your first example). In the expression after ":=", the expression "list" will contain whatever list you input (so if you call sort[x], then the definition is executed where list = x).
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook