Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I want to define a function with more than one formula, but I don't know how. For example, I want to define a function f which f[1] = RandomInteger[{0, 1}] and f[2] = RandomInteger[{0, 3}]. I searched the web, Mathematica.SE and the Mathematica help, but I just found the function Piecewise, which didn't work.

share|improve this question
The good news is that you already have a solution. Evaluate your code as it is (EDIT: no, change = in :=), and then try f[1] and f[2]. You will get the result you want. –  Peltio Dec 3 '13 at 17:42
Which is wrong with using the good old fashioned Which? f[x_] := Which[x == 1, RandomInteger[{0, 1}], x == 2, RandomInteger[{0, 3}], {}] or you if you want to be fancy, f[x_] /; x == 1 := RandomInteger[{0, 1}]; f[x_] /; x == 2 := RandomInteger[{0, 3}] –  Nasser Dec 3 '13 at 17:42
I think Peltio and Nasser should place their comments as the answers. –  Alexei Boulbitch Dec 5 '13 at 9:25
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.