2
$\begingroup$

I would like to create a Table for the value of a function $f(x,y)$, the form of which changes depending on the ranges of $x$ and $y$. For instance, $f=x+y$ for $x\in [1,2]$ and $y\in [0,1]$ while $f=x-y$ for $x\in [2,3]$ and $y\in [1,2]$.

I tried the following code, which didn't work.

Flatten[Table[{{x + y, x, y}, {x, 1, 2, 0.1}, {y, 0, 1, 0.1}}, {{x - y, x, y}, {x, 2, 3, 0.1}, {y, 1, 2, 0.1}}], 1] // TableForm

Any help would be greatly appreciated!

$\endgroup$
  • $\begingroup$ Just define your function as a piecewise function and build the table of values as normal? $\endgroup$ – Kevin Ausman Jul 18 at 18:40
  • $\begingroup$ @KevinAusman: Thanks! Since this code is part of a larger project, I'm seeking a solution that uses the current format as much as possible. Would this be possible? $\endgroup$ – ppp Jul 18 at 18:44
5
$\begingroup$

Here is a way to salvage your attempt to get the values in the form I believe you were trying to get them in:

spec = {
   {{x + y, x, y}, {x, 1, 2, 0.1}, {y, 0, 1, 0.1}},
   {{x - y, x, y}, {x, 2, 3, 0.1}, {y, 1, 2, 0.1}}
   };
Flatten[Table @@@ spec, 1]

But this question also brings to mind Piecewise, which can be used to express functions like the one in your question:

f = Piecewise[{
   {x + y, 1 <= x < 2 && 0 <= y < 1},
   {x - y, 2 <= x <= 3 && 1 <= y <= 2}
   }]

Mathematica graphics

You can now get the table of values like this:

values = Table[f, {x, 1, 3, 0.1}, {y, 0, 2, 0.1}];
$\endgroup$
  • $\begingroup$ Thanks so much! It works! $\endgroup$ – ppp Jul 19 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.